简体   繁体   English

如何执行在另一页中写在一页中的JavaScript?

[英]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: 与其将JavaScript写入页面,不如将其写入.js文件(即script.js),然后使用script标签引用.js文件:

<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 我不确定为什么要问这个问题,但是如果您的动机只是重用JavaScript代码,那么您实际上可以将代码分解为一个单独的.js文件,并通过执行以下操作从不同页面调用它

<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. 如果您使用window.open打开一个新窗口,则可以使用window.opener对象从新窗口中获取对父对象的引用,而window.open本身将返回对打开页面的引用。 Example: 例:

Page A: 页面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: 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(); 在一个页面中,在隐藏的iframe中打开另一页,然后在document.getElementById('targetFrame')。contentWindow.targetFunction();中执行javascript代码。

Note: Both the pages should be served from the same domain otherwise there will be XSS issues. 注意:两个页面都应从同一域提供,否则将存在XSS问题。

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. 例如,如果A.aspx是您的父页面,并且使用javascript window.open()打开页面B.aspx,则B.aspx将是子页面。 Then you can call A.aspx javascript function from B.aspx using window.opener instead of window.parent which I posted earlier. 然后,您可以使用window.opener而不是我先前发布的window.parent从B.aspx调用A.aspx javascript函数。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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