使用JavaScript和DOM获取当前页面的源代码 [英] Obtain current page's source using javascript and DOM

查看:809
本文介绍了使用JavaScript和DOM获取当前页面的源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得使用当前页的源代码的JavaScript DOM ? 我将不得不使用 AJAX

解决方案

当前页面的HTML,所呈现:

  document.documentElement.outerHTML
 

另外,你可以使用的innerHTML ,但你只能得到的含量<身体GT; 标记。

当前页面的HTML,作为检索的页面加载:

动态与AJAX调用重新查询页面。

使用jQuery(坦途):

任何其他现代JavaScript库将允许做同样的事情,但为了举例,用jQuery这将是:

  $。阿贾克斯(window.location.href,{
  成功:功能(数据){
    的console.log(数据);
  }
});
 

使用XMLHtt prequest对象(更复杂的):

显然下去裸骨的路线,你需要自己处理一些事情,包括跨浏览器的支持,但它的要点是:

  VAR请求=新XMLHtt prequest();

request.open(GET,window.location.href,假);
request.send();

如果(request.status === 200){
  执行console.log(request.responseText);
}
 

How do I obtain the current page's source using JavaScript and DOM? Would I have to use AJAX?

解决方案

For the current page's HTML, as rendered:

document.documentElement.outerHTML

Alternatively, you could use innerHTML, but you'd only get the content of the <body> tag.

For the current page's HTML, as retrieved on page load:

Re-query the page dynamically with an AJAX call.

Using jQuery (easy path):

Any other modern JavaScript library would allow to do something similar, but for the sake of example, with jQuery it would be:

$.ajax(window.location.href, {
  success: function (data) {
    console.log(data);
  }
});

Using the XMLHttpRequest object (more involved):

Obviously going down the bare-bone route, you'll need to handle a few more things yourself, including cross-browser support, but the gist of it would be:

var request = new XMLHttpRequest();

request.open('GET', window.location.href, false);
request.send();

if (request.status === 200) {
  console.log(request.responseText);
}

这篇关于使用JavaScript和DOM获取当前页面的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆