开发者

How to execute JavaScript writen in one page from another page?

How do I execute JavaScript written in one aspx page开发者_如何学Go from another aspx page?


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>


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();
}


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜