在JavaScript中,获取当前网页的源代码可以通过多种方式实现。以下是一些常见的方法:
document.documentElement.outerHTML
这是最常用的方法之一,可以直接获取整个HTML文档的源代码。
let htmlSource = document.documentElement.outerHTML;
console.log(htmlSource);
fetch
API如果你想通过HTTP请求获取当前页面的源代码,可以使用fetch
API。
fetch(window.location.href)
.then(response => response.text())
.then(htmlSource => {
console.log(htmlSource);
})
.catch(error => {
console.error('Error fetching the page:', error);
});
XMLHttpRequest
这是一个较老的方法,但在某些情况下仍然有用。
let xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
let htmlSource = xhr.responseText;
console.log(htmlSource);
}
};
xhr.send();
fetch
或XMLHttpRequest
时,需要处理异步操作。确保在数据完全加载后再进行处理。通过上述方法,你可以有效地获取当前网页的源代码,并根据具体需求进行相应的处理和应用。
领取专属 10元无门槛券
手把手带您无忧上云