0

I want to dynamically load some javascript on a page. I have the idea to make a content script that will check some condition for choosing which scripts to load.

My problem is that I don't know how to load a script. I have already tried JQuery getScript() function but it use unsafe-eval call. I have also found chrome.tab.executeScript() but it can't be use in Content scripts.

I have to do it form Content Script because it have to check some contion on the page BEFORE loading scripts. I don't want to load all my scripts each time a page is loaded.

Is it possible ?

Emrys Myrooin
  • 2,179
  • 14
  • 39

1 Answers1

1
  1. Send a message to your background page and in the message listener download the external script with XMLHttpRequest or jQuery.ajax to a variable and insert it with chrome.tab.executeScript({code: downloadedCode}); or as a webpage script

  2. Include these scripts in your extension, list them in "web_accessible_resources" and inject as a webpage script setting the added <script> element's src attribute to chrome.runtime.getURL("that_script_name").

Community
  • 1
  • 1
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • I know I can do this. But it's not what I'm asking for. I want to load my scripts form a content script. Because I will not load always the same script. I choose which script I want to load by checking some condition on the content of the page. – Emrys Myrooin Sep 11 '15 at 13:46
  • Send a message to your background page from the content script. Or use the second method from the answer. What's the problem? – wOxxOm Sep 11 '15 at 13:47
  • Humm yes I haven't think about send a message with the list of script to load... It's an idea. But all the content of the script will be global... I wanted to do some thing like an "include" in other languages... – Emrys Myrooin Sep 11 '15 at 13:51
  • What do you mean `content of the script will be global`? You can insert the new script into the tab that sent the message, I can add an example if needed. – wOxxOm Sep 11 '15 at 13:52
  • I mean that defined function in that script will be added to the global namespace. And I only need it in the definition of one of my Angular Controllers. But I don't think it's possible to do better... – Emrys Myrooin Sep 11 '15 at 13:54