[英]unable to send message from background script to content script in chrome extension
I cannot send message from my background script to content script except i remove the popup.html from the browser action in the manifest.json. 我无法从后台脚本向内容脚本发送消息,除非我从manifest.json中的浏览器操作中删除了popup.html。 Someone help me
谁来帮帮我
background.js 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 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 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 - Except this is removed from the manifest.json i cannot send message from background to content.js. popup.html-除非从manifest.json中删除,否则我无法将消息从后台发送到content.js。 Please note i use the console function to check if the message was sent across to the content.js
请注意,我使用控制台功能来检查消息是否已发送到content.js
According to documentation , the chrome.browserAction.onClicked
listener is 根据文档 ,
chrome.browserAction.onClicked
侦听器是
Fired when a browser action icon is clicked.
单击浏览器操作图标时触发。 Does not fire if the browser action has a popup.
如果浏览器操作弹出,则不会触发。
(bold type added). (已添加粗体)。
Either remove the browserAction popup or move the code you currently have inside the listener to the popup page script. 要么删除browserAction弹出窗口,要么将当前在侦听器中拥有的代码移到弹出页面脚本中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.