在JavaScript中,获取当前页面的源码可以通过不同的方法实现。以下是几种常见的方法:
document.documentElement.outerHTML
这种方法可以获取整个HTML文档的源码,包括<head>
和<body>
部分。
let pageSource = document.documentElement.outerHTML;
console.log(pageSource);
fetch
API通过fetch
API请求当前页面的URL,然后获取响应内容。
fetch(window.location.href)
.then(response => response.text())
.then(pageSource => {
console.log(pageSource);
})
.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 pageSource = xhr.responseText;
console.log(pageSource);
}
};
xhr.send();
通过上述方法,你可以有效地获取当前页面的源码,并根据具体需求进行相应的处理和应用。
领取专属 10元无门槛券
手把手带您无忧上云