There is an extension that displays "123" on a specific page.

manifest.json

{ "manifest_version": 2, "name": "name", "version": "1.0.0.0", "description": "description", "content_scripts":[{ "matches": [ "http://ru.stackoverflow.com/*" ], "js": [ "content_scripts.js" ] }] } 

content_scripts.js

 alert(123); 

It is necessary to add a button, when clicked, the function will be executed. Suppose so enter image description here

document.querySelector('.topbar').innerHTML = '<a onclick="myfunction(\'show\');">Какая-то надпись</a>';

Next, add the function function myfunction(text){ alert(text); } function myfunction(text){ alert(text); } However, this does not work. Error: Uncaught ReferenceError: myfunction is not defined .

I know that you can take the script to a separate file, and then just connect it.

 var New_js = document.createElement('script'); New_js.type = 'text/javascript'; New_js.src = 'log.js'; document.getElementsByTagName('head')[0].appendChild(New_js); 

Or add through:

document.querySelector('.topbar').addEventListener("click", function(){myfunction("show")}, false);

I would like to keep everything in one file.

Tell me, please, what other options are there?

And why the standard one does not work - function myfunction(text){ alert(text); } function myfunction(text){ alert(text); } ?

1 answer 1

Uncaught ReferenceError: myfunction is not defined

The functions at the time of the call are not yet in the heap. Why - this is a good question that you will not answer without a code.
It is necessary to addEventListener processor through addEventListener , forget archaisms like onclick .
And it will work in one file.