0

In my content script, I am using this approach to be able to access web page's variables:

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script); //run the script
    document.body.removeChild(script); //clean up
}

exec( function(){
    var test = websiteVar

    chrome.runtime.sendMessage("extensionID", {test: test}, function(response) {

    });
});

Where it says extensionID, if I hardcode it, it works. However, I can't use chrome.runtime.id as it is injected in the page. I think I read they don't work in the same context.

Is there a way to get the extension id programatically?

senty
  • 12,385
  • 28
  • 130
  • 260
  • In my answer to: [Calling webpage JavaScript methods from browser extension](https://stackoverflow.com/a/40572286) I provide a generalized solution to executing a function in the page context from a content script while passing arguments to the function. You could use that to just pass the extensionId as a value, obtained from `chrome.runtime.id`. – Makyen Sep 16 '17 at 06:55
  • 1
    Yeah, simply pass it as a parameter `+ ')(' + chrome.runtime.id + ');';` and use it in the function. – wOxxOm Sep 16 '17 at 09:01

1 Answers1

6

Example of what wOxxOm said above:

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')("' + chrome.runtime.id +'")';
    document.body.appendChild(script); //run the script
    document.body.removeChild(script); //clean up
}

exec( function(extensionID){

    var test = websiteVar;
    chrome.runtime.sendMessage(extensionID, {test: test}, function(response) {

    });

});
Luka Čelebić
  • 1,083
  • 11
  • 21