I have been trying to use iframe
to load a cross-origin webpage onto my website but it is not functioning as expected. When I load my website, sometimes the iframe doesn't load the webpage at all and when it does load, its document
is null
.
Here is the script file (which is included at the end of the <body>
)
var iframe = document.getElementById('myFrame');
iframe.onload = function() {
alert('iframe loaded!');
if(iframe.contentWindow)
{
alert('contentWindow checked');
}
if(iframe.contentWindow.document)
{
alert('document checked');
}
}
When I load the page, I only get the "iframe loaded!" and "contentWindow checked" alerts. This also happens when the webpage doesn't load at all. For some reason the document
is always null
even when the webpage loads fine in the iframe
.
I am using the Chromium web browser.
I have been trying to use iframe
to load a cross-origin webpage onto my website but it is not functioning as expected. When I load my website, sometimes the iframe doesn't load the webpage at all and when it does load, its document
is null
.
Here is the script file (which is included at the end of the <body>
)
var iframe = document.getElementById('myFrame');
iframe.onload = function() {
alert('iframe loaded!');
if(iframe.contentWindow)
{
alert('contentWindow checked');
}
if(iframe.contentWindow.document)
{
alert('document checked');
}
}
When I load the page, I only get the "iframe loaded!" and "contentWindow checked" alerts. This also happens when the webpage doesn't load at all. For some reason the document
is always null
even when the webpage loads fine in the iframe
.
I am using the Chromium web browser.
- 1 Per the console error I get, Chrome blocks access to the cross-origin document. – user5734311 Commented Jun 30, 2018 at 10:54
- 1 You can't access document of cross domain iframe due to "same origin policy" – charlietfl Commented Jun 30, 2018 at 10:54
- 1 Can I turn it off for any other browser? – AvZ Commented Jun 30, 2018 at 11:18
1 Answer
Reset to default 2The contentWindow property returns the Window object generated by an iframe element (through the window object, you can access the document object and then any one of the document's elements). You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only. hence iframe.contentDocument.
var iframe = document.getElementById('myFrame');
iframe.onload = function() {
alert('iframe loaded!');
let contentWindow = (iframe.contentWindow || iframe.contentDocument) //this is better approach
if(iframe.contentWindow)
{
alert('contentWindow checked');
}
if(iframe.contentDocument)
{
alert('document checked');
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744652008a4585955.html
评论列表(0条)