jQuery获取整个iframe源代码,包括<html>之外的注释

jQuery get entire iframe source including comments outside <html>

本文关键字:html 注释 获取 iframe 源代码 jQuery 包括      更新时间:2023-09-26

问题 如何使用jQuery获取整个页面的HTML?可能看起来很相似,这有助于从<html><!DOCTYPE>获取数据。但除此之外,我还需要获取在 <html> 标签之前保留的任何注释。

我正在使用jQuery在srcdoc属性的帮助下显示页面。我当前获取数据的代码是

$("#myiframe").contents().find('html')[0].outerHTML;

以及此答案中的片段以获取<!DOCTYPE html>

示例用例:

<!-- 
  This comment will be used for further processing
--> 
<!DOCTYPE html>
<html lang='en'>
<head>
...
</head>
<body>
...
</body>
</html>
<!-- 
  This comment will be used for further processing
-->

电流输出仅为<!DOCTYPE html></html>。预计会在外面发表评论。

看看jQuery的$.get函数。 这基本上返回了您将使用正常GET请求检索的所有内容。https://api.jquery.com/jquery.get/

试试这个:

$('iframe#myiframe').load(function() {
  getFrameContent(this.contentWindow.location);
});
function getFrameContent(windowURL) {
   $.get( windowURL, function( data ) {
     //where 'data' is the page contents
     $( "#whateverElementYouWant" ).html( data );
  });
}