【发布时间】:2018-12-01 23:42:01
【问题描述】:
我正在使用内容脚本(加载有run_at: document_start 来尝试在从 JavaScript 进行任何 DOM 修改之前获取页面的确切源。
我想要纯 HTML - 正是您在浏览器中从 Right Click > View Source 获得的内容。
我尝试了两种几乎都有效但并不完全有效的方法。
这是页面的实际原始来源,来自Right Click > View Source
<!doctype html>
<html lang="en">
<head>
<title>Raw HTML title</title>
</head>
<body>
<p>Something here.</p>
<script>
document.title = 'Title injected by JS';
</script>
</body>
</html>
我尝试过的事情:
新的 XMLSerializer().serializeToString(document)
这会产生以下内容:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>Raw HTML title</title>
</head>
<body>
<p>Something here.</p>
<script>
document.title = 'Title injected by JS';
</script></body></html>
很接近,但由于某种原因格式不正确,“doctype”大写,xmlns 属性添加到<html> 标记。
document.documentElement.outerHTML
产生以下内容:
<html lang="en"><head>
<title>Raw HTML title</title>
</head>
<body>
<p>Something here.</p>
<script>
document.title = 'Title injected by JS';
</script></body></html>
</body></html>
缺少文档类型,格式也与原始格式不符。
【问题讨论】:
-
通过
document访问总是会给你浏览器对 HTML 的解释,后期渲染。 -
内容脚本无法获得“在从 JavaScript 进行任何 DOM 修改之前页面的确切来源”,因为当浏览器加载页面时,它还必须处理内联脚本无论您是否想要修改页面。不过,您可以获得服务器响应,但您必须使用确切的 URL 和 cookie 发出单独的 XHR/fetch 请求。
-
@wOxxOm
new XMLSerializer().serializeToString(document)和document.documentElement.outerHTML都在这样做,注意标题标签是原始 HTML 标题,在修改之前。问题是格式不一样,添加了一些额外的属性
标签: javascript google-chrome-extension