[英]Chrome onMessage Listener not getting called
I am experimenting with the chrome.extension
API. 我正在尝试使用chrome.extension
API。
manifest.json 的manifest.json
{
"name": "First",
"version": "1.0",
"manifest_version": 2,
"description": "First extension",
"background": {
"scripts": ["test.js"]
},
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "display.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions" : [
"tabs",
"http://*/*", "https://*/"
]
}
display.js display.js
alert("inside display.js");
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse){
alert("inside msg");
var time = request.sel_text;
alert(time);
});
test.js test.js
function check(tab_id, data, tab){
if(tab.url.indexOf("google") > -1){
chrome.pageAction.show(tab_id);
chrome.tabs.executeScript(null, {"file" : "display.js"}) ;
}
};
chrome.tabs.onUpdated.addListener(check);
popup1.js popup1.js
function myfunc(){
var x = $('#options option:selected').text();
alert(x);
chrome.extension.sendMessage({sel_text: x});
}
$(document).ready(function(){
$('#options').change(myfunc);
});
Now, when my page loads I get three(3)
popups saying inside display.js
but chrome.extension.onMessage.addListener
is never called. 现在,当我的页面加载时,我会inside display.js
输入three(3)
弹出窗口,但从不调用chrome.extension.onMessage.addListener
。
So, what am I doing wrong. 那么,我做错了什么。 Can we can access chrome.extension.*
API from content script. 我们可以从内容脚本访问chrome.extension.*
API吗?
chrome.extension.sendMessage
only triggers onMessage
listeners in the extension's scope, excluding content scripts . chrome.extension.sendMessage
仅在扩展的范围内触发onMessage
侦听器, 不包括内容脚本 。
You can notify content scripts using the chrome.tabs.sendMessage
method, as follows: 您可以使用chrome.tabs.sendMessage
方法通知内容脚本,如下所示:
function myfunc() {
var x = $('#options option:selected').text();
var message = {sel_text: x};
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tabId = tabs[0].id;
chrome.tabs.sendMessage(tabId, message);
});
}
chrome.extension.sendMessage({sel_text: x});
which is in popup1.js
not used or referenced in your manifest file. 在清单文件中未使用或引用的popup1.js
中。 Where are you using popup1.js
in your extension? 你在扩展中使用popup1.js
在哪里?
chrome.extension.onMessage.addListener is fired when a message is sent from either an extension process or a content script, you don't have any messages being sent in your code!. 当从扩展进程或内容脚本发送消息时,会触发chrome.extension.onMessage.addListener ,您的代码中没有发送任何消息!
Moreover, why do you want re-inject script chrome.tabs.executeScript(null, {"file" : "display.js"}) ;
此外,为什么要重新注入脚本chrome.tabs.executeScript(null, {"file" : "display.js"}) ;
from background page
while it is already registered with manifest file
. 从background page
虽然它已经注册了manifest file
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.