我无法从后台脚本向内容脚本发送消息,除非我从manifest.json中的浏览器操作中删除了popup.html。有人帮我
background.js
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tabs) {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(tabs[0].id, {"message": "clicked_browser_action"});
});
});
// This block is new! and will be used later
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "open_new_tab" ) {
chrome.tabs.create({"url": request.url});
}
}
);
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message == "clicked_browser_action" ) {
console.log("Congratulations you can now work!");
// This line is new!
chrome.runtime.sendMessage({"message": "open_new_tab", "url": firstHref});
}
}
);
manifest.json
{
"name": "Wowprezi lead tool",
"version": "1.0",
"description": "Extension to find leads and add to sales force!",
"author": "Djouonang Landry",
"manifest_version": 2,
"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
"background": {
"persistent": true,
"scripts": ["js/background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/jquery-3.3.1.min.js","js/content.js"],
"all_frames": true
}
],
"browser_action": {
"default_popup": "html/popup.html",
"default_title": "Find leads"
}
}
popup.html-除了从manifest.json中删除外,我无法将消息从后台发送到content.js。请注意,我使用控制台功能来检查消息是否已发送到content.js
答案 0 :(得分:1)
根据documentation,chrome.browserAction.onClicked
侦听器为
在单击浏览器操作图标时触发。 如果 浏览器操作会弹出。
(已添加粗体)。
要么删除browserAction弹出窗口,要么将当前在侦听器中拥有的代码移动到弹出页面脚本。