Sub*_*way 76 background sendmessage google-chrome-extension content-script
我知道这个问题已经以不同的方式反复提出,但我试图通过所有的答案(希望我没有错过任何人),但没有一个对我有用.
这是我的扩展程序代码:
表现:
{
"name": "test",
"version": "1.1",
"background":
{
"scripts": ["contextMenus.js"]
},
"permissions": ["tabs", "<all_urls>", "contextMenus"],
"content_scripts" : [
{
"matches" : [ "http://*/*" ],
"js": ["jquery-1.8.3.js", "jquery-ui.js"],
"css": [ "jquery-ui.css" ],
"js": ["openDialog.js"]
}
],
"manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)
contextMenus.js
function onClickHandler(info, tab) {
if (info.menuItemId == "line1"){
alert("You have selected: " + info.selectionText);
chrome.extension.sendMessage({action:'open_dialog_box'}, function(){});
alert("Req sent?");
}
}
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"id": "line1", "type": "normal", "title": "I'm line 1", "contexts":["selection"]});
});
Run Code Online (Sandbox Code Playgroud)
openDialog.js
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'open_dialog_box') {
alert("Message recieved!");
}
});
Run Code Online (Sandbox Code Playgroud)
后台页面的两个警报工作,而其中一个content_script没有.
控制台日志的消息:端口错误:无法建立连接.接收端不存在.
我的错在哪里?
aps*_*ers 126
在您的背景页面中,您应该致电
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {});
});
Run Code Online (Sandbox Code Playgroud)
而不是chrome.extension.sendMessage
像你现在一样使用.
所述chrome.tabs
变体将消息发送到内容的脚本,而chrome.extension
功能将消息发送到所有其它的扩展部件.
小智 16
@apsillers 是正确的。也不要忘记在您的内容脚本侦听器中返回 true 否则它可能会过早关闭。
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message)
return true
});
Run Code Online (Sandbox Code Playgroud)
小智 7
所提供的解决方案的问题是它们会引发其他错误(这会破坏我的 Google Chrome)
@apsillers 解决方案有效,但回调会引发错误!
它应该是什么样子
// 背景.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"});
});
Run Code Online (Sandbox Code Playgroud)
现在在 @Ronan Ca 提供的内容脚本中,该脚本基于 @apsillers 解决方案构建。由于我们从后台脚本中删除了回调,因此返回并不理想。
// 内容脚本.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message)
// return true <- this and the callback in background.js are what caused a crash in extensions page of my Google chrome
});
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用回调来打开后台控制台,则后台控制台将不会打开。(这次车祸真是太糟糕了)
归档时间: |
|
查看次数: |
51255 次 |
最近记录: |