gpt4 book ai didi

google-chrome-extension - 来自 Chrome 扩展的消息传递示例

转载 作者:行者123 更新时间:2023-12-04 00:30:44 24 4
gpt4 key购买 nike

我正在使用 the Google tutorial 中的示例并且发现很难从弹出窗口向内容脚本传递简单的消息。

您能否就如何传递简单消息并在控制台日志或警报中查看它提供一些建议?

manifest.json

{
"manifest_version": 2,

"name": "msg-test",
"description": "message test",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},

"background": {
"scripts": ["background.js"],
"persistent": true
},

"content_scripts": [{
"matches": ["http://*/*","http://www.site.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}],

"permissions": [
"tabs",
"http://*/*"
]
}

背景.js
chrome.runtime.onConnect.addListener(function(port){
port.postMessage({greeting:"hello"});
});

内容.js
var port = chrome.runtime.connect({name:"content"});
port.onMessage.addListener(function(message,sender){
if(message.greeting === "hello"){
alert(message.greeting);
}
});

popup.js
window.onload = function() {

document.getElementById('btn2').onclick = function() {
alert("button 2 was clicked");
};

document.getElementById('btn1').onclick = function() {
alert("button 1 was clicked");
};


}

*注意:在本例中,内容脚本将在页面匹配 manifest.json 时触发,并显示警告框。

最佳答案

首先,我不会在您的弹出窗口和您的内容脚本之间传递消息。我会在您的 Background page 之间传递消息和你的内容脚本。您的弹出页面应该只用于显示一些与您的应用程序交互的用户界面。

话虽如此,我将向您展示在您的背景和内容脚本之间传递消息的方法。

在您的内容脚本中:

//This line opens up a long-lived connection to your background page.
var port = chrome.runtime.connect({name:"mycontentscript"});
port.onMessage.addListener(function(message,sender){
if(message.greeting === "hello"){
alert(message.greeting);
}
});

在您的背景页面中(可能是您的弹出窗口?但我不推荐它)
chrome.runtime.onConnect.addListener(function(port){
port.postMessage({greeting:"hello"});
});

以下是将要发生的事件顺序:
  • 您的应用程序会将您的内容脚本注入(inject)到页面
  • 您的内容脚本将打开一个端口以与后台脚本进行通信。
  • 您的后台脚本将收到一个端口已打开的通知,允许它向其发送消息,或向其附加消息监听器。

  • 在后台脚本或内容脚本中,您可以使用 port.onMessage.addListener() 收听消息。 .前提是该端口在范围内。使用端口更容易掌握,并且允许简单的双向通信!

    编辑:

    如果您想从弹出脚本将消息传递到后台页面,请使用完全相同的方法:
    var port   =   chrome.runtime.connect({name: "popup-port"});
    port.postMessage({status:"poppedup"});

    编辑2:

    要将用户导航到新页面,请执行以下操作:
    function navigateToPage(url){
    chrome.tabs.query({url: url}, function(tabs) {
    var tab = tabs[0];
    return tab ? chrome.tabs.update(tab.id, {active:true}) : chrome.tabs.create({url: url});
    });
    }
    });

    这个函数的作用是,它检查是否有一个带有您要访问的 url 的选项卡,如果有,切换到它,否则,使用该 url 创建一个选项卡并导航到它。

    关于google-chrome-extension - 来自 Chrome 扩展的消息传递示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21766990/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com