Dart chrome extension: Listen to chrome api events

To better describe my problem, I created a small example of a chrome extension written in Dart. You can see the code or download the extension on Gist .

Problem

This example works fine in Dartium, but when compiling in javascript there is a problem with typeerror: Uncaught TypeError: undefined is not a functionfor string:

context['chrome']['runtime']['onMessage'].callMethod('addListener', [onMessageListener]);

As far as i am already

  • As you can see in this example, js-extension functions also work with functions alert()or console.log()through dart:js. So this could be a particular problem with dart2js and adding eventlisteners?
  • The printout also context['chrome']['runtime']['onMessage']shows the correct event object. (For example context['console'].callMethod('log', [context['chrome']['runtime']['onMessage']]);)
  • I know that there is a chrome pub package, but an error still occurs when replying to received messages in onMessage. See also question . Using chrome api directly through dart: js was a workaround that was great in this version of the dart.

I played a lot with the code, but all the results are in the same error. Now I have no ideas. Hope the community helps me again.

Edit: Now I reported this error to dartbug.com , as Robert suggested. Anyway, I'm still open to a workaround or something if someone knows it.

+3
source share
2 answers

keerti: .

:

  //Tmp: sendResponse is buged, so we use the js-version
  //chrome.runtime.onMessage.listen(onMessageDartListener);

  //..and ofcourse the js-version is buged too. So this workaround here:
  var jsOnMessageEvent = context['chrome']['runtime']['onMessage'];
  JsObject dartOnMessageEvent = (jsOnMessageEvent is JsObject ? jsOnMessageEvent : new JsObject.fromBrowserObject(jsOnMessageEvent));
  dartOnMessageEvent.callMethod('addListener', [onMessageListener]);
0

, :

//Placed in web/

import 'dart:js';

void main() {
  //This doesnt work in js
  context['chrome']['runtime']['onMessage'].callMethod('addListener', [onMessageListener]);
  context['chrome']['runtime'].callMethod('sendMessage', ['someMessage']);
  context['chrome']['runtime'].callMethod('sendMessage', [null, 'someMessage']);
}


void onMessageListener(message, sender, sendResponse) {
  print("test");
  print(message);
}

test (:1)
someMessage (:1)
test (:1)
someMessage (:1)

,

// ,

www.dartbug.com

,

// -. :

import 'dart:js';
import 'package:chrome/chrome_ext.dart' as chrome;

void onMessageListener(message, sender, sendResponse) {
  print("test");
  print(message);
}

void main() {
  chrome.runtime.onMessage.listen((chrome.OnMessageEvent event) {
    print(event.message);
  });

  JsObject runtime = context['chrome']['runtime'];
  runtime.callMethod('sendMessage', ['someMessage']);
  runtime.callMethod('sendMessage', [null, 'someMessage']);
}

,

+2

Source: https://habr.com/ru/post/1529545/


All Articles