问题
I have the following problem when running dart2js
compiled version of my chrome extension:
Uncaught TypeError: undefined is not a function
when executing
context['chrome']['runtime']['onConnect'].callMethod('addListener', [(port) { ... }]);
I have created an example which possibly points to the cause:
background.dart
import 'dart:js';
void main() {
print("main(): context['chrome']['runtime']['onConnect'] (${context['chrome']['runtime']['onConnect'].runtimeType}): ${context['chrome']['runtime']['onConnect']}");
}
prints in Dartium:
main(): context['chrome']['runtime']['onConnect'] (JsObject): [object Object]
but in Chrome:
main(): context['chrome']['runtime']['onConnect'] (Event): Instance of 'Event'
Is it related to Difference between Dartium and dart2js when building chrome extensions (https://code.google.com/p/dart/issues/detail?id=17086)?
Could someone suggest how to register chrome.runtime.onConnect
listener which would work in both Dartium and Chrome?
回答1:
After looking at common.dart
in chrome.dart
package:
void _ensureHandlerAdded() {
if (!_handlerAdded) {
// TODO: Workaround an issue where the event objects are not properly
// proxied in M35 and after.
var jsEvent = _api[_eventName];
JsObject event = (jsEvent is JsObject ? jsEvent : new JsObject.fromBrowserObject(jsEvent));
event.callMethod('addListener', [_listener]);
_handlerAdded = true;
}
}
it seems necessary to wrap Event
into JsObject
to make it working in dart:js
.
The same was required for the following too:
- port.onDisconnect
- port.onMessage
If someone knows of an existing issue tracking this problem, please feel free to add it.
来源:https://stackoverflow.com/questions/25193392/issue-with-chrome-runtime-onconnect-when-building-chrome-extension-in-dart