Emrys Myrooin
Emrys Myrooin

Reputation: 2231

Dynamical script loading in content script

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 ?

Upvotes: 0

Views: 126

Answers (1)

woxxom
woxxom

Reputation: 73836

  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").

Upvotes: 1

Related Questions