Dart chrome 扩展:监听 chrome api 事件

2024-05-03

为了更好地描述我的问题,我创建了一个用 Dart 编写的 chrome 扩展的小示例。 您可以在以下位置查看代码或下载扩展程序Gist https://gist.github.com/andigehle/a09ac9b765097bb84a65.

问题

这个示例在 Dartium 中运行良好,但是当编译为 javascript 时,会出现类型错误:Uncaught TypeError: undefined is not a function对于该行:

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

我已经走了多远

  • 正如您在示例中看到的功能alert() or console.log() via dart:js也在 js 扩展中工作。那么这可能是 dart2js 和添加事件监听器的一个特殊问题?
  • 也打印出来context['chrome']['runtime']['onMessage']显示正确的事件对象。 (例如。:context['console'].callMethod('log', [context['chrome']['runtime']['onMessage']]);)
  • 我知道有一个chrome pub包,但是在onMessage中响应收到的消息时仍然存在错误。另请参阅此question https://stackoverflow.com/questions/22114022/dart-chrome-extension-how-to-send-a-response-in-onmessage。直接通过 dart:js 使用 chrome api 是解决方法,在该 dart 版本中效果很好。

我对代码进行了很多操作,但都导致了相同的错误。现在我没有主意了。希望社区能够再次帮助我。

Edit:我现在已经报告了这个错误dartbug.com https://code.google.com/p/dart/issues/detail?id=20800正如罗伯特建议的那样。 无论如何,如果有人知道的话,我仍然愿意寻求解决方法或其他方法。


所以你的例子对我来说效果很好:

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

问候, 罗伯特

// 抱歉错过了你得到的异常

您应该在 www.dartbug.com 上提交有关此问题的错误

问候, 罗伯特

// 现在您应该能够使用 chrome 包。它在这里工作得很好:

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

问候, 罗伯特

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Dart chrome 扩展:监听 chrome api 事件 的相关文章

随机推荐