简体   繁体   中英

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

如何执行在另一个aspx页面中的一个aspx页面中编写的JavaScript

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

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM