javascript Chrome 扩展程序 sendMessage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11531139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:33:28  来源:igfitidea点击:

Chrome extension sendMessage

javascriptgoogle-chromegoogle-chrome-extensionsendmessage

提问by Tom B

The documentation here seems terrible: http://code.google.com/chrome/extensions/messaging.html

这里的文档看起来很糟糕:http: //code.google.com/chrome/extensions/messaging.html

I want my content script, simply to show a pageIcon if there is a textarea on the page.

我想要我的内容脚本,如果页面上有文本区域,只需显示一个 pageIcon。

My content.js (using jquery) does this:

我的 content.js(使用 jquery)这样做:

$('textarea').each(function() {
    chrome.extension.sendMessage({greeting: "hello"}, function(response) {
       console.log(response);
    });
});

Then my background.js has this:

然后我的 background.js 有这个:

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
});

Which should be incredibly simple. If there's a textarea, show the icon.

这应该非常简单。如果有文本区域,则显示图标。

I have tried all kinds of variations from sample code and nothing works. All I ever get is:

我已经尝试了示例代码中的各种变体,但没有任何效果。我得到的只是:

Port error: Could not establish connection. Receiving end does not exist.

端口错误:无法建立连接。接收端不存在。

in the console.

在控制台中。

Any ideas where I'm going wrong?

任何想法我哪里出错了?

回答by ron

I think you have an extra curly bracket in the background script.

我认为您在后台脚本中有一个额外的大括号。

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
});

should be

应该

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
);