I'm trying to execute the onclick() event of a link (<a>), but it does not take the visitor anywhere, it executes JavaScript code. However, how can I execute the code, considering that content scripts don't have access to the scripts on the webpage they run in? The code that should be executed uses custom functions, that are declared in the webpage.
-
why can't you put the javascript you need to access in external files?Remi– Remi2011-09-02 16:48:25 +00:00Commented Sep 2, 2011 at 16:48
-
It's not my webpage, and I prefer not to carry such code in my files.Bogdacutu– Bogdacutu2011-09-02 17:24:32 +00:00Commented Sep 2, 2011 at 17:24
Add a comment
|
1 Answer
what about (using jquery):
suppose the script-in-page contains the function 'myfunc' that you want to be able to execute.
var script = $( "#webscript" ); (or any other way to get the script tag that contains the code)
var myfunc = null; // declare the function-name (perhaps even not necessary)
eval(script.html()); // where myfunc is declared and assigned to your myfunc variable
now try to use the function:
myfunc();
Edit2: you can probably also 'insert' the code again:
var copyScript = document.createElement('script');
copyScript.type = 'text/javascript';
copyScript.text = script.html();
document.head.appendChild(copyScript);
4 Comments
Bogdacutu
I already tried doing
eval() with the code that is in onclick: it will not work because the function needed isn't declared.Remi
that's why you need to declare it, using the string literal that contains the actual code copied as text using .html()
Bogdacutu
Oh, it seems I misunderstood it. But, if the page is dynamic, how could I declare the code? It should work on any page, without modification on my side.
Remi
perhaps you can loop through and 'analyse' the script tags for containing the code you want (e.g. does its text contain 'myfunc = function(' ), before you use eval() on it.