通过js打开新窗口时执行javascript [英] Execute javascript when opening new window via js

查看:954
本文介绍了通过js打开新窗口时执行javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javascript打开一个新窗口并将内容写入新窗口。部分内容是javascript文件,但javascript不会在新窗口中执行。帮助?



open.html:

 <   script  >  
function winopen()
{
var ghtml =< h1 > sasaasas < / h1 > ;
var gwin = window.open(,_ blank,location = no,width = 1000,height = 600);
if(gwin)
{gwin.document.open();
gwin.document.write(ghtml);

var oscript = gwin.document.createElement(script);
oscript.type =text / javascript;
oscript.src =open.js;
gwin.document.getElementsByTagName(head)[0] .appendChild(oscript);

//gwin.document.close();
}
}
winopen();
< / script >





open.js:

 function init(){ alert(  winwin); } 
setTimeout(function(){init();}, 2000 );

解决方案

在您的代码中,您没有显示任何应该触发脚本执行的内容。解决方案很简单:您应该将一些脚本放置为元素body或html元素的子元素。另一种方法是将属性 onload 添加到< body> 元素中(例如,参见https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body [ ^ ] )。由于您没有显示您创建的窗口的HTML内容,我不确定您是否尝试这样做,很可能不会。



-SA

I am opening a new window using javascript and write content to the new window. Part of the content is a javascript file, but the javascript does not execute in the new window. Help?

open.html:

<script>
function winopen()
{
  var ghtml = "<h1>sasaasas</h1>";
  var gwin = window.open("", "_blank", "location=no,width=1000,height=600");
  if (gwin)
  { gwin.document.open();
    gwin.document.write(ghtml);

    var oscript = gwin.document.createElement("script");
    oscript.type = "text/javascript";
    oscript.src = "open.js";
    gwin.document.getElementsByTagName("head")[0].appendChild(oscript);

    //gwin.document.close();
  }
}
winopen();
</script>



open.js:

function init() { alert("winwin"); }
setTimeout(function() { init(); }, 2000);

解决方案

In your code, you did not show anything which should trigger execution of your script. The solution is simple: you should have some script placed as a child of the element "body" or your "html" element. Another approach is adding the attribute onload to the <body> element (see, for example https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body[^]). As you did not show your HTML content of your created window, I am not sure if you tried to do so, most likely not.

—SA


这篇关于通过js打开新窗口时执行javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆