How to get element and html from window.open js function with jquery

亡梦爱人 提交于 2019-11-29 07:15:13

Try:

var html = popup.document.documentElement.outerHTML

EDIT

The window is not loaded immediately. Something like this will work, assuming that you're not attempting to violate the same-origin policy:

$('#btn').click(function() {
    var popup = window.open('[Your URL HERE]', '_blank', 'width=500,height=500');

    popup.onload = function() {
        setTimeout(function(){ console.log(popup.document.documentElement.outerHTML) }, 2000);
    }  
});​

Here's a working fiddle.

Note: If you control both the parent and the child source, you could also have the child invoke a method on the parent that passes in it's html:

Child Window

// Call when body is loaded
function SendHtmlToParent() {
    window.opener.HtmlReceiver(document.outerHTML);
}

Parent

function HtmlReceiver(html) {
    console.log(html);
}

Wait...

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

MDN

And if you wait, you will get this error:

Unsafe JavaScript attempt to access frame with URL https://www.google.co.il/ from frame with URL http://fiddle.jshell.net/_display/. Domains, protocols and ports must match.

So it can be done with google, unless you're working there...

Fiddle

If you open something "valid" it will work fine.

Working DEMO

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!