【问题标题】:message passing from web page to contentscript.js in chrome extension [duplicate]消息从网页传递到 chrome 扩展中的 contentscript.js [重复]
【发布时间】:2015-10-22 12:53:53
【问题描述】:

想要从浏览器中的页面向 chrome 扩展中的 contentscript.js 发送一个状态值,方法是向新创建的事件添加一个值,并将其传递给扩展,但接收值为“未定义”。 代码如下。

page.html

<html>
<head></head>
<body>
<script>
    var go = function() {
    var sam=1;
        var event = document.createEvent('Event',{"details": 1});
        event.foo=sam;
        event.initEvent('hello');
        document.dispatchEvent(event);
    }
</script>
<a href="javascript:go();">Click me</a>
</body>
</html>

我正在尝试访问 'foo' 和 'status'(其中一个)的值,但将这两个值都设为 'undefined'。

contentscript.js

document.addEventListener("hello", function(data) {
    alert("test:foo "+data.foo+":"+data.status);
})

请告诉我如何访问该值。

【问题讨论】:

  • 我不会对自己太苛刻。只需用东西填充隐藏的 dom 元素,然后让您的扩展程序在加载后从 dom 读取数据。你真的不必用纯js来做
  • 嗨@Thou Art Amazing,我可以得到一些关于这个主题的示例链接吗?

标签: javascript google-chrome-extension google-chrome-devtools


【解决方案1】:
 Based on documentation from: [https://developer.chrome.com/extensions/messaging#external-webpage][1]

    - manifest.json

    "externally_connectable": {
      "matches": ["*://<your extension id>/*/page.html"]
    }

    page.html:
    // The ID of the extension we want to talk to.
    var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

    // Make a simple request:
    chrome.runtime.sendMessage(editorExtensionId, {"details": 1},
      function(response) {
        if (!response.success)
          handleError(url);
      });

    contentscript.js

    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if (sender.url === blacklistedWebsite)
          return;  // don't allow this web page access
        if (request.details)
          //process message
      });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多