Issue with chrome.runtime.onConnect when building

2019-05-10 07:38发布

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条回答
Summer. ? 凉城
2楼-- · 2019-05-10 08:02

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.

查看更多
登录 后发表回答