Send a request for nested content Script on ContextMenu Click

I entered the code on every page the user visits. But I want this script to run when the user clicks on the Menu context created by the same extension. In short, I need to pass a message between background.html and the script content, but the trigger should happen when the context menu is clicked.

Here is what I 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 this is happening. From what I understood, something is wrong in tabs.getSelected with tab.id as the first parameter. But since the source of the click is the context menu, maybe it does not read tab.id or does not understand which tab I am working on.

+4
source share
1 answer

First of all, the error is between chrome.extension.sendRequest and chrome.tabs.sendRequest . Your method signatures are incorrect for sendRequest , it lacks a parameter (which is not optional). The first parameter is the "extension identifier", in which case it must be zero.

If you want to send a message to 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 onRequest . You still need the first parameter, which is your tab identifier.

 chrome.tabs.getSelected(null, function(tab) { chrome.tabs.sendRequest(tab.id, {"variable1":x,"type":"y"}); }); 
+6
source

Source: https://habr.com/ru/post/1343514/


All Articles