【问题标题】:chrome extension OnMessagechrome 扩展 OnMessage
【发布时间】:2012-12-02 07:07:29
【问题描述】:

我是 Chrome 扩展程序的新手,当然我坚持每一步,但这特别难。也许这是一个愚蠢的错误,但这是我想要做的:

从内容脚本向后台页面发送一条简单的消息,并将其作为变量处理。所以我的内容脚本中有这个:

$(document).ready(function() { 
    var d = document.domain;    
       chrome.extension.sendMessage({dom: d});  

 });

在我的后台脚本中:

chrome.extension.onMessage.addListener(function(request) {
    alert(request.dom);
});

所以,警报工作正常。但它“进入”我正在浏览的页面,而不是 HTML 扩展,这意味着,当点击我的扩展按钮时,它不会弹出,而是在页面加载时被编码到内容脚本中。

请,任何帮助将不胜感激。

【问题讨论】:

  • 我不确定您在期待什么,但基于But it "goes" to the page I am browing and not the HTML extension, this means, instead of poping up when clicking on my extension button, it will appear as it was coded into the content script when the page loads. 我假设您仅在单击扩展按钮后才期待警报()?如果这是真的,那么你就错了,因为你在后台脚本而不是在浏览器操作中添加了监听器,这是预期的行为,如果你能清楚地发布所有相关的代码和期望,那就太好了,所以我们可以帮助你.
  • 感谢您的回复。基本上我想要做的只是将一个值从内容脚本传递到后台脚本。然后将它分配给一个变量并处理它(在后台脚本中),然后在单击我的扩展图标时在弹出窗口中显示该值。我之前发布的代码基本上是我到目前为止所做的一切。如何将其添加到浏览器操作中?简单地说:你会怎么做我想做的事?提前致谢。

标签: google-chrome background google-chrome-extension


【解决方案1】:

我的Demo扩展如下

文件和角色

a) manifest.json (Documentation)

b) myscript.js(内容脚本见Documentation

c) background.js(背景 HTML 文件参见Documentation

d) popup.html(浏览器操作弹出窗口见Documentation

e) popup.js(后台页面修改值的接收器)

manifest.json

将所有文件注册到具有权限的清单(即背景、弹出窗口、内容脚本)

{
"name":"Communication Demo",
"description":"This demonstrates modes of communication",
"manifest_version":2,
"version":"1",
"permissions":["<all_urls>"],
"background":{
    "scripts":["background.js"]
},
"content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["myscript.js"]
    }
  ],
"browser_action":{
    "default_icon":"screen.png",
    "default_popup":"popup.html"
}  
}

myscript.js

使用sendMessage() API与后台页面通信

var d = document.domain;
chrome.extension.sendMessage({
    dom: d
});

background.js

使用 onMessage()onConnect() 监听器为 Content 和 popup.js 添加了事件监听器

var modifiedDom;
chrome.extension.onMessage.addListener(function (request) {
    modifiedDom = request.dom + "Trivial Info Appending";
});
chrome.extension.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (message) {
        if (message == "Request Modified Value") {
            port.postMessage(modifiedDom);
        }
    });
});

popup.html

示例浏览器操作 HTML 页面注册 popup.js 以避免Inline Scripting

<!doctype html>
<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body></body>

</html>

popup.js

使用Port\Long Lived Connection 与后台页面通信以获取结果

var port = chrome.extension.connect({
    name: "Sample Communication"
});
port.postMessage("Request Modified Value");
port.onMessage.addListener(function (msg) {
    console.log("Modified Value recieved is  " + msg);
});

希望对您有所帮助,如果您需要更多信息,请告诉我

【讨论】:

  • 重要提示chrome.extension 的消息传递功能已被弃用。使用 chrome.runtime 等效项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多