将内容添加到新的打开窗口

Mar*_*ero 41 html javascript jquery

我不知道如何解决这个问题,我尝试阅读很多帖子,但没有人回答.

我需要打开一个新窗口,其中包含已经编码的页面(在同一个域内)并添加一些内容.

问题是,如果我使用OpenWindow.write()的页面尚未加载,或者它会覆盖所有内容,只会显示通过写入添加的代码.

var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(output);
Run Code Online (Sandbox Code Playgroud)

output 是我需要追加的代码.

我需要它至少在Firefox,IE和GC上工作.

提前致谢.如果我需要使用JQuery,这不是问题.

ieg*_*gik 51

当您想要打开新标签/窗口时(取决于您的浏览器配置默认值):

output = 'Hello, World!';
window.open().document.write(output);
Run Code Online (Sandbox Code Playgroud)

当输出是a Object并且你想获得JSON时(例如,也可以生成任何类型的文档,甚至是在Base64中编码的图像)

output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));
Run Code Online (Sandbox Code Playgroud)

更新

谷歌浏览器(60.0.3112.90)阻止此代码:

Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9

当您想要将某些数据附加到现有页面时

output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;

output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;
Run Code Online (Sandbox Code Playgroud)


Ray*_*eng 26

parent.html:

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("child.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
        OpenWindow.init();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

child.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>
Run Code Online (Sandbox Code Playgroud)


Set*_*ath 7

这是你可以尝试的

  • 在mypage.html里写一个函数说init()做html的事情(追加或者什么)
  • 当dom准备好时,而不是OpenWindow.document.write(output);打电话OpenWindow.init()

所以父窗口会有

    OpenWindow.onload = function(){
       OpenWindow.init('test');
    }
Run Code Online (Sandbox Code Playgroud)

在孩子身上

    function init(txt){
        $('#test').text(txt);
    }
Run Code Online (Sandbox Code Playgroud)