简体   繁体   English

.contentWindow.document.body.outerHTML无法正常工作?

[英].contentWindow.document.body.outerHTML Not Working?

I have the following JavaScript code: 我有以下JavaScript代码:

myFrame.src = pathToCourseContents + "/otherComponents/myData.htm";

After this line is executed: 执行此行后:

myFrame.src equals "http://myServer.com/otherComponents/myData.htm"

If I put this URL address into FireFox I do get a web page with information coming up. 如果我将这个URL地址放入FireFox中,则会显示一个网页,其中包含即将出现的信息。

What I'm trying to get is the contents of myData.htm in the form of a string. 我想要获取的是字符串形式的myData.htm内容。

I thought this would work: 我认为这可以工作:

var myString = myFrame.contentWindow.document.body.outerHTML

but myFrame.contentWindow appears to be blank. 但myFrame.contentWindow似乎为空。

What am I doing wrong? 我究竟做错了什么?

Is there JavaScript code that will work to get the html content in the form of a string? 是否有JavaScript代码可用于以字符串形式获取html内容?

您可以尝试使用以下方法:

document.getElementsByTagName("html")[0]

contentWindow is most often blank when you load url from diferent domain. 当您从其他域加载url时, contentWindow通常为空白。 It is prohibitied to access such content, because of security. 出于安全考虑,禁止访问此类内容。 If this is your case, you're doomed (well, there are workarounds, like proxy through the server that serves the container page, so that browser thinks they are from the same domain; or set document.domain in both files, if you control both of them; etc.). 如果是这种情况,那您就注定要失败(好吧,有一些解决方法,例如通过服务于容器页面的服务器代理,以便浏览器认为它们来自同一域;或者,如果您在两个文件中都设置document.domain,控制它们两者;等等。

If you're not encountering the same origin policy, it may be that you're trying to access nodes before they exist (ie before the DOM is ready). 如果您没有遇到相同的原始策略,则可能是您尝试在节点存在之前(即在DOM准备就绪之前)访问节点。

A simple solution is to add an event listener on the <iframe> for the load event. 一个简单的解决方案是在<iframe>load事件添加一个事件侦听器。

myFrame.addEventListener('load', function () { // add a listener
    console.log( // do what you want
        '<iframe> loaded\n',
        myFrame.contentWindow,   // the <iframe>'s Window
        myFrame.contentDocument, // the <iframe>'s document
        '\n',
        myFrame.contentDocument.body.outerHTML
    );
});
// set src after so that listener exists before event raised
myFrame.src = 'http://fiddle.jshell.net/'; // same origin pass

example fiddle 小提琴的例子

.contentWindow get's cleared every time you refresh so you can't add page load listeners to it that will give you the result you want, but you can listen for other events from within the <iframe> there. 每次刷新时,都会清除.contentWindow因此您无法向其添加页面加载侦听器,这将为您提供所需的结果,但是您可以在<iframe>监听其他事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM