Andi
Andi

Reputation: 234

Dart chrome extension: Listen to chrome api events

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

The problem

This example is running fine in Dartium, but when compiled to javascript a typeerror occurs: Uncaught TypeError: undefined is not a function for the line:

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

How far i already am


I played a lot with the code but all results in the same error. Now i am out of ideas. Hope the community can help me again.

Edit: I have now reported this bug on dartbug.com as Robert suggested. Anyway, I'm still open for a workaround or something if someone know one.

Upvotes: 3

Views: 716

Answers (2)

Andi
Andi

Reputation: 234

As keerti already mentioned: A similar problem with a workaround can be find here.

My solution looks like this:

  //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]);

Upvotes: 0

Robert
Robert

Reputation: 5662

So your example is working fine for me:

//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);
}

Output

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

Regards, Robert

// Sorry missed the exception you get

You should file a bug about this at www.dartbug.com

Regards, Robert

// For now you should be able to use the chrome package. It works fine here:

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']);
}

Regards, Robert

Upvotes: 3

Related Questions