消息从网页传递到chrome扩展中的contentscript.js

时间:2015-10-22 12:53:54

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

想要从浏览器中的页面向chrome extension中的contentscript.js发送状态值,通过向新创建的事件添加值将其传递给扩展名,但是接收值为' undefined&# 39 ;. 代码如下。

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>

我试图获得&#39; foo&#39;的价值。和&#39;状态&#39;(其中任何一个),但将两个值都定义为&#39; undefined&#39;。

contentscript.js

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

请让我知道如何访问该值。

1 个答案:

答案 0 :(得分:0)

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