tags:

views:

111

answers:

5

How do I execute JavaScript written in one aspx page from another aspx page?

+2  A: 

You cannot do this. Instead of writing your JavaScript to a page, write it to a .js file (i.e.: script.js) and then reference the .js file with a script tag:

<script type="text/javascript" src="script.js"></script>
mattbasta
A: 

In one page open the other page in a hidden IFrame and execute the javascript code in the hidden iframe as document.getElementById('targetFrame').contentWindow.targetFunction();

Note: Both the pages should be served from the same domain otherwise there will be XSS issues.

GeekTantra
+1  A: 

The short answer is that you can't.

I'm not sure why you're asking this, but if your motivation is just to reuse the JavaScript code, then you can actually factor the code out into a separate .js file and call it from different pages by doing

<script type="text/javascript" src="your_javascript_file.js"></script>

in those pages.

Edwin Lee
Thnks for reply The thing is a have a page A.aspx there is script in that which will create a tab . from A i m opening another page B.aspx . what i want is when i click a button in B.aspx .The script in A.aspx should execute . or else the link in A.aspx which call that script should execute ...
jazz
hmm. Question is, that script in A.aspx, what is it supposed to do?
Edwin Lee
A: 

It is possible only when there is a parent-child relationship between pages. For example, if A.aspx is your parent page and you open page B.aspx using javascript window.open(), then B.aspx will be the child page. Then you can call A.aspx javascript function from B.aspx using window.opener instead of window.parent which I posted earlier.

Thanks.

Hoque
`window.parent` is for accessing the parent from a frame. `window.opener` is what you need.
Andy E
Thanks for correcting me.
Hoque
A: 

If you're using window.open to open a new window, you can use the window.opener object to get a reference to the parent object from the new window and window.open itself will return a reference to the open page. Example:

Page A:

var newWin = window.open("pageB.aspx");  // ref to pageB is stored in var newWin
newWin.onload = function () 
{
    newWin.helloB();
}
function helloA()
{
    // Run the alert method inside the new window
    newWin.alert("Hello from page A!");
}

page B:

var opener = window.opener; // Ref to pageA is stored in var opener
opener.helloA(); // call to opener's helloA function
function helloB()
{
    // Run the alert method inside the opener window
    opener.alert("Hello from page B!");
}

// We can do the same thing in an event that occurs on this page
var btn = document.getElementById("pageBButton");
btn.onclick = function ()
{
    window.opener.helloA();
}
Andy E