我想创建一个chrome扩展名,可以做到这一点:
在我的popup.html中,我这样做:
$("#openLink").click(function () {
chrome.runtime.sendMessage({greeting: "GetURL"},
function (response) {
});
});
此后,我单击此按钮,我收到此消息并在此处创建一个新标签:(background.js)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "GetURL") {
var tabURL = "Not set yet";
chrome.tabs.create({
url: "http://google.de"
}, function (tab) {
//chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function (response) {
});
});
}
});
如您所见,我得到了选项卡ID,并尝试向该选项卡发送消息。但是如何在内容脚本中获取该消息? 我用这个,但是不起作用:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
alert('s');
console.log('s');
});
答案 0 :(得分:0)
我建议的解决方案是将您的后台脚本修改为inject the content script programmatically,例如:
background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "GetURL") {
var tabURL = "Not set yet";
chrome.tabs.create({url: 'http://google.de'}, function (tab) { //create tab
chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function(){ //inject content script
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}); //send message to content script
});
});
}
});