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.

Bogdacutu
  • 763
  • 7
  • 24

1 Answers1

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);
Community
  • 1
  • 1
Remi
  • 20,619
  • 8
  • 57
  • 41
  • I already tried doing `eval()` with the code that is in `onclick`: it will not work because the function needed isn't declared. – Bogdacutu Sep 02 '11 at 17:46
  • that's why you need to declare it, using the string literal that contains the actual code copied as text using .html() – Remi Sep 02 '11 at 17:48
  • 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. – Bogdacutu Sep 02 '11 at 17:49
  • 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. – Remi Sep 02 '11 at 17:52