简体   繁体   English

如何获取iframe的全部确切内容并进行编辑?

[英]How do I grab the entire exact contents of an iframe and also be able to edit it?

I know you can get the innerHTML doing something like this, with jQuery, 我知道您可以使用jQuery让innerHTML做类似的事情,

$('iframe').load(function(){
  alert($(this).contents().find('body').html());
});

This gets the innerHTML of the body tag. 这将获取body标签的innerHTML。 But I want it all. 但是我想要这一切。 I want the HTML tag and the doctype. 我想要HTML标记和doctype。 The whole source code basically. 整个源代码基本上。 And I want to be able to edit it as a whole as well. 而且我也希望能够对其进行整体编辑。 By "as a whole", I mean I wanna be able to do something like this, 所谓“整体”,是指我想做这样的事情,

$('iframe').html('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>title</title>
</head>
<body>
hello world
</body>
</html>');

How do I do this? 我该怎么做呢?

Note: I realize DOM is handled differently in different browsers and so the innerHTML from Opera will look different than the one from Firefox. 注意:我意识到DOM在不同的浏览器中的处理方式有所不同,因此Opera的innerHTML外观与Firefox的不同。 But it's no biggie. 但这没什么大不了的。

I assume this document you are accessing is on the same server? 我假设您要访问的文档位于同一服务器上? Obviously being able to access (and edit!) the contents of another website would be very dangerous. 显然,能够访问(和编辑!)另一个网站的内容将非常危险。

$('iframe').contentWindow.document.documentElement.outerHTML will contain the full html tag and its contents. $('iframe').contentWindow.document.documentElement.outerHTML将包含完整的html标记及其内容。 outerHTML isn't exactly cross-browser, and you may want to parse the attributes of the documentElement object instead. outerHTML并非完全跨浏览器,您可能想解析documentElement对象的属性。 Note that you can't edit the outerHTML (at least in WebKit), so you can use innerHTML to edit the contents. 请注意,您不能编辑externalHTML(至少在WebKit中),因此可以使用innerHTML编辑内容。

$('iframe').contentWindow.document.doctype represents the DOCTYPE. $('iframe').contentWindow.document.doctype代表DOCTYPE。 You can't get the actual tag, but you can retrieve the information from its attributes. 您无法获得实际的标签,但是可以从其属性中检索信息。 Here is the MSDN reference for the !DOCTYPE element. 是!DOCTYPE元素的MSDN参考。

document.write is your friend. document.write是您的朋友。

For example: 例如:

var iframeEl = document.createElement('iframe');
document.body.appendChild(iframeEl);

var oFrame = window.frames[window.frames.length - 1];
oFrame.document.write('<html><head><title>foo</title></head><body>bar</body></html>');

oFrame.document.body.innerHTML; // "bar"

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

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