Chrome extension: insert javascript tag and function call

I have a chrome extension that uses script content to dynamically insert a script tag that references external javascript . The code I'm using is:

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);

External Javascript contains the following code:

function lfunc(){
  alert('RUNNING loaded function');
}
alert('LAST LINE of script');

When I load the page in a tab, the message "LAST LINE of script" appears, indicating that the script tag is correctly inserted into the DOM.

My extension also has a button (i.e. browser_action). Now I would like this button to call lfunc (), defined above whenever it is clicked. Unfortunately, my code just doesn't work .

I use the following code on the background.html page to handle the onClick event of my button:

<script>
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, 
    {code: "try {lfunc()} catch (e) {alert(e);}"});
  }); // it should call lfunc()
</script>

manifest.json:

"permissions": [
"tabs", "http://*/*", "https://*/*"  ]

"RUNNING loaded function" "ReferenceError: lfunc ".

?

+3
3

JS ( DOM (document )). JS DOM.

:

  • Javascript ( ) :
    JS jQuery, document.body.
  • Javascript ( JS JS) :
    API- Chrome, , , , ..

.

, (sendRequest onRequest), - "content script" script/background pages. =) .

> JS -

.

> , , , JS DOM. , JS

. Ext JS .., JS ( -).

> JS, JS

JS function level? JS?

PS
chrome.tabs.executeScript , . , script (, content_scripts). , , content_scripts: DOM JS-, JS. :

// Inside a `background_page`:
chrome.tabs.executeScript(null, {
    "code": "document.body.removeChild(document.body.firstChild);"
});

, ( ) DOM. (, jQuery ):

// Still inside a `background_page`:
chrome.tabs.executeScript(null, {
    "code": "jQuery('input').remove();"
});

, jQuery - , , JS-, ( background_page content_scripts).
, Chrome =). , ...

BTW
, ... browser_action JS DOM. , ? JS . , JS browser_action (). : (= JS browser_action).

: JS . () .

+9

alert('It doesn't work'); alert(e);

, . .

+1

I needed to call a function that was inside one of the page scripts ...

location = 'javascript:callToTheFunction(param,param,..)' did it.  

I speak from the content

+1
source

All Articles