0

Is there a way to know whether the content script has been injected successfully. I know we can use message passing. But is there a way other than that??

2 Answers2

2

I think the easiest way would be to use the optional callback to executeScript. End your content script with 'success'; on its own line. Then your injection call would be:

chrome.tabs.executeScript(tabId, details, successStatus);
function successStatus(frameResults) {
  if ( frameResults[0] === 'success' ) {
    // successfully injected
  }
}
Teepeemm
  • 4,331
  • 5
  • 35
  • 58
  • what do u mean by adding 'success'. – Nishan Miranda Oct 13 '15 at 16:50
  • `frameResults` is an array, where each array element is the last evaluated expression in the content script in a frame. So you want your content script to end with an expression that indicates it successfully loaded. In this case, you can simply write `'success';` on its own line. Chrome will evaluate that expression, and that will be the entry in the results array. – Teepeemm Oct 13 '15 at 16:58
  • i added just as u said..but receiving null – Nishan Miranda Oct 13 '15 at 17:21
  • thank you...got it..if i'm injecting via a file the last line must be json serializable – Nishan Miranda Oct 14 '15 at 07:03
0

Ok so say we are talking of the actual page and not the background extension.

First you must include the scrits in the page, here is how im doing this

var j = document.createElement('script');
j.src = chrome.extension.getURL('bower_components/jquery/dist/jquery.min.js');
(document.head || document.documentElement).appendChild(j);

var k = document.createElement('script');
k.src = chrome.extension.getURL('bower_components/jquery-ui/jquery-ui.min.js');
(document.head || document.documentElement).appendChild(k);

And then to check if it was loaded i have a an if condition

if( (/in/.test(document.readyState)) || (undefined === Backbone) ) {
    setTimeout('refresh(' + f + ')', 10);
  } else {
    f();
    console.log("Loaded Main Application");

So i ask if the state is ready and then check if the browser loaded my js.

Hope it helps

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30
  • OP is using executeScript in a background/event page, so he's injecting differently than you. (And don't use the eval form of `setTimeout`. In this case, you should use `refresh.bind(undefined,f)`.) – Teepeemm Oct 13 '15 at 15:14