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

I am trying to open a popup like this:

$('#btn').click(function () { var popup = window.open('mypage.php', '_blank', 'width=500,height=500'); var dom = popup.document.body; for (i in dom) { console.log(dom[i]); } }); 

Now what I want to do is get the html from the popup window and also use the jQuery function from the window.opener window (the page that opened the popup window)

PS. There are a lot of printed materials in the console, but there is no html source.

Use this to try: http://jsfiddle.net/JRqTy/

Thanks in advance.

+4
source share
2 answers

Try:

 var html = popup.document.documentElement.outerHTML 

EDIT

The window does not load immediately. Something like this will work, assuming you are not trying to violate a policy of the same origin :

 $('#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 the parent and child source, you can also force it to call the method of the parent element that passes html in it:

Children's window

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

Parent

 function HtmlReceiver(html) { console.log(html); } 
+2
source

Wait...

Please note that remote URLs will not load immediately. When window.open () returns, the window always contains about: blank. The actual URL fetch is delayed and starts after the current script block completes. Window creation and link resource loading are performed asynchronously.

MDN

And if you wait, you will get this error:

Insecure JavaScript is trying to access the frame from the URL https://www.google.co.il/ from a frame with the URL http://fiddle.jshell.net/_display/ . Domains, protocols, and ports must be consistent.

So it can be done with google if you don’t work there ...

Fiddle

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

Working demo

+1
source

Source: https://habr.com/ru/post/1402709/


All Articles