2012-03-21 41 views
4

我試圖打開一個像這樣的彈出:如何從window.open js函數獲取元素和HTML與jQuery

$('#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]); 
    } 
}); 

現在我想要做的是讓從彈出窗口中的HTML和也可以使用window.opener中的jQuery函數(打開彈出窗口的頁面)

PS。在控制檯中有很多東西打印出來,但沒有html源代碼。

使用此嘗試:提前http://jsfiddle.net/JRqTy/

感謝。

回答

2

嘗試:

var html = popup.document.documentElement.outerHTML 

編輯

不會立即加載的窗口。這樣的事情會工作,假設你沒有試圖違反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); 
    } 
});​ 

這裏的a working fiddle

注:如果你同時控制父母和孩子源,您也可以將孩子調用一個方法在穿過它的HTML父:

子窗口

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

家長

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

稍候...

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

如果你等待,你會得到這樣的錯誤:

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.

因此,它可以與谷歌做的,除非你在那裏工作。 ..

Fiddle

如果你打開一些事情「有效」它會正常工作。

Working DEMO

+1

@OscarJara。我們清除了評論中的所有主題。這是一團糟。 – gdoron 2012-03-21 18:47:36

相關問題