0

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.

2
  • why can't you put the javascript you need to access in external files? Commented Sep 2, 2011 at 16:48
  • It's not my webpage, and I prefer not to carry such code in my files. Commented Sep 2, 2011 at 17:24

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I already tried doing eval() with the code that is in onclick: it will not work because the function needed isn't declared.
that's why you need to declare it, using the string literal that contains the actual code copied as text using .html()
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.