Note that there are some explanatory texts on larger screens.

plurals
  1. POChrome extension: inserting a javascript tag and calling a function
    text
    copied!<p>I have a chrome extension that uses a <strong>content script</strong> in order to dynamically insert a script tag referencing <a href="http://unixpapa.com/js/dyna1.js" rel="nofollow">an external javascript file</a>. The code I use is:</p> <pre><code>var html_doc = document.getElementsByTagName('head')[0]; var _js = document.createElement('script'); _js.setAttribute('type', 'text/javascript'); _js.setAttribute('id', 'chr_js'); _js.setAttribute('src', 'http://unixpapa.com/js/dyna1.js'); if(!document.getElementById('chr_js')) html_doc.appendChild(_js); </code></pre> <p>The external Javascript contains the following code:</p> <pre><code>function lfunc(){ alert('RUNNING loaded function'); } alert('LAST LINE of script'); </code></pre> <p>When I load a page in a tab the "<em>LAST LINE of script</em>" message appears, showing that the script tag is correctly inserted in the DOM. </p> <p>My extension also has a <strong>button</strong> (i.e., a browser_action). Now, I would like this button to call <em>lfunc()</em> defined above whenever it is clicked. Unfortunately, <strong>my code simply doesn't work</strong>.</p> <p>I use the following code in the <em>background.html</em> page to process the onClick event of my button:</p> <pre><code>&lt;script&gt; chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(null, {code: "try {lfunc()} catch (e) {alert(e);}"}); }); // it should call lfunc() &lt;/script&gt; </code></pre> <p>The permissions in the <em>manifest.json</em> file are:</p> <pre><code>"permissions": [ "tabs", "http://*/*", "https://*/*" ] </code></pre> <p>Instead of getting the "<em>RUNNING loaded function</em>" message I get the error message "<em>ReferenceError: lfunc is not defined</em>". </p> <p>What am I doing wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload