Send Request to injected Content Script on ContextMenu Click
I have injected a code into every page that the user visits. But I want this script to be triggered when the user clicks on the contextMenu thats created by the same extension. In short I have to pass message between the background.html and content script but the trigger should happen on click of context menu.
Here is what I have tried
//background.html
function subFunction(info,tab){
var x = info.selectionText;
alert("x");//This is working fine
chrome.tabs.getSelected(null, function(tab) {
chrome.extension.sendRequest({"variable1":x,"type":"y"});
});
}
chrome.contextMenus.create({"title": "Submit", "onclick": subFunction,"contexts":['selection']});
//myscript.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
alert("Seems like I am in");
if(request.type == 'y'){
alert("This is" + request.x);
}
});
Can anyone tell me where is this going wrong. From what I understood something is开发者_如何学运维 wrong about the tabs.getSelected with the tab.id as the first parameter. But as the source of the click is the context menu, may be its not reading the tab.id or it doesn't understand on which tab I am working on.
First of all mistaken between chrome.extension.sendRequest
and chrome.tabs.sendRequest
. Your method signatures are incorrect for sendRequest
, it is missing a parameter (which isn't optional). The first parameter is the "extension id" in this case it should be null.
If you want to send a message to the other extension pages, you use chrome.extension.sendRequest
. If you want to send a message to your content script, you need to use chrome.tabs.sendRequest
.
In this, case you need to use chrome.tabs.sendRequest
since your onRequest
listener is living there. You still need a first parameter which is your tab id.
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {"variable1":x,"type":"y"});
});
精彩评论