繁体   English   中英

如何在新打开的窗口中运行 Javascript?

[英]How to run Javascript in newly opened window?

假设我有以下代码。

window.open(url, windowName, "height=500,width=500") 
// This will open a new window with the url.

myFunction();
// Run this function on the newly opened window instead of
// the old one because I need to find a link on the new page.

现在, myFunction() 卡在旧窗口上。

更新:新的 url 是另一个域。

myFunction()放在新窗口的脚本中。

然后设置该窗口的onLoad事件以运行它。

您可以通过以下方式从新窗口中获取对调用方窗口文档的引用:

window.opener.document

你有足够的链接来做几乎任何事情。

更新:

您的新窗口应该来自同一个域。 否则它违反浏览器的同源策略

请看这个问题:

规避同源策略的方法

您有多种选择:

  1. 编辑存储在url的网页的源代码,以包含您希望在网页打开时运行的自定义代码。 如果您只想在网页从弹出窗口打开时运行此代码,您可以将 url 命名为“webpage.html?run_custom_code”,然后在 webpage.html 中使用仅在window.location.href.indexOf('run_custom_code') > 0

  2. 你可以打开一个网页,它的唯一目的是运行 javascript: window.open('javascript:alert()'); 尽管根据您的编辑,这对您来说似乎没有用。

  3. 使用另一种语言,例如 PHP,您可以在其中使用$html = file_get_contents($url);类的内容获取另一个网页的内容$html = file_get_contents($url);

  4. 对另一个 url 执行ajax 请求(如果它位于同一个域中)并抓取结果以找到您的链接。

暂无
暂无

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

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