1

I was wondering if it is possible in anyway to inject a javascript file instead of just code statements.

for example (what works):

chrome.devtools.inspectedWindow.reload({
  ignoreCache: true,
  injectedScript: 'console.log("Hello World!")'
});

but I want to see if I can inject a .js file (doesn't work):

chrome.devtools.inspectedWindow.reload({
  ignoreCache: true,
  injectedScript: 'file.js'
});

2 Answers2

2

No, this API doesn't allow it, but it's not hard to write a wrapper that does:

  1. Request file.js using XHR.
  2. Call reload with the response as injectedScript.

For example:

function reloadWithFile(scriptFile) {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function(evt) {
    chrome.devtools.inspectedWindow.reload({
      ignoreCache: true,
      injectedScript: xhr.responseText
    });
  });
  xhr.open("GET", chrome.runtime.getURL(scriptFile));
  xhr.send();
}

Injecting multiple files by concatenating them is left as an exercise (Promises may be helpful).

Xan
  • 74,770
  • 16
  • 179
  • 206
1

I think that is not or not yet possible to do. But there are other workarounds like inject the file using the content.js or using the background.js chrome.tabs.executeScript(). You might want to check using a content script js file and background.js

Community
  • 1
  • 1
Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91
  • 1
    I thought of that, but the problem is with what `reload()` does. It effectively does a one-time injection of a `run_at: "document_start"` content script. This is going to be very tricky to implement due to timing involved - you can't `executeScript` on the "new" page until navigation is committed, and my that time it may be too late to inject before the page's own scripts. – Xan May 13 '16 at 09:15
  • Thank for pointing out some info that I missed, up voting your answer – Mr.Rebot May 14 '16 at 06:30