0

I am trying to write a Chrome Extension, which calls on a function injected into some sites via content script. The script runs fine when called through browser console, but doesn't work via tabs.executescript because it seems to be faster than the injection of the content script (therefore calling on empty functions)

ExecuteScript Call:

chrome.tabs.executeScript(tab.id, {
    code: 'var nummer = ' + nummer + '; var tabURL = "' + taburl + '";'
}, function() {
    chrome.tabs.executeScript(tab.id, {
    file: "launch-script-manually.js"
    }, function() {
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
        }
    });
});
function launch (url, name, callOnLoad) {
  window.open(url, name)
    .addEventListener(
      "load",
      callOnLoad,
      { once: true, passive: true }
    );
}

function proceed (evt) {
  console.log("A window has been loaded");
  console.log(evt);
  if(evt.currentTarget.checkbtn(nummer) == 1) {
      console.log("It worked!" + evt);
  }
  else {
      document.body.innerHTML = document.body.innerHTML + "Window" + evt + "Failed<br>"
  }
}

async function launchProcess (taburl) {
  document.body.innerHTML = "";
  const sleep3 = { then(resolve) { setTimeout(resolve, 250); } };
  for (let i = 2; i < 7; ++i) {
    launch(taburl, "tab" + i, proceed);
    await sleep3;
  }
}
launchProcess(tabURL);

This results in a console error:

Uncaught TypeError: evt.currentTarget.checkbtn is not a function at proceed (launch-script-manually.js:24)

However, if I run it manually through console, it works out fine!

How do I fix this, so that it will run through the executeScript call?

Ranger
  • 75
  • 7
  • You need to dig a level deeper and [Insert code into the page context using a content script](//stackoverflow.com/a/9517879) – wOxxOm Aug 03 '19 at 14:27
  • So you're saying that I need to insert the script.js file which contains function checkbtn in the proceed(evt) function? Help me out here a little please, because I don't get it :( – Ranger Aug 03 '19 at 14:56
  • In your launch-script-manually.js you'll create a `'script'` element. Its `textContent` or `src` points to the code that will run in the page context. That code can access `checkbtn`, but it can't call content script functions directly, it can only communicate via standard DOM messaging as shown [here](https://stackoverflow.com/a/19312198). – wOxxOm Aug 03 '19 at 15:01
  • Okay, got it! So if I want a return to launch-script I must use DOM messaging... am i right? And if I don't want a return from checkbtn, I could just use the plain script element injection to call checkbtn()? – Ranger Aug 03 '19 at 15:04

0 Answers0