我正在使用一个Chrome扩展程序来阻止网站,但未使用Chrome内置的阻止方法。进行自定义的原因是,我需要为每个被阻止的网站显示一个自定义阻止页面-相同的模板,并提供有关为何阻止该特定网站的详细信息。
在我的content.js
文件中,我将一个“此站点被阻止”页面的完整HTML模板存储在一个称为var的变量中template
(因为我不知道从Extension中的文件中加载它,所以我每天都是Python编码人员... )。清单包含大量URL,因此,如果加载了content.js脚本,则应阻止此站点(或检查该站点是否在本地允许用户使用“无论如何都允许”)。如果应该阻止某个站点,那么我要做的唯一事情就是:
var template = `<html>...full web page template removed...</html>`;
chrome.runtime.sendMessage({method: "getSite", site: window.location.host.toString()}, (response) => {
console.log(response.data);
document.body.innerHTML = renderTemplate(template, response.data);
});
renderTemplate函数仅采用HTML并进行一些查找+替换为response.data-这是有关URL的数据,该数据是从后台脚本中获取的,后台脚本只是带有大量词典的.js文件。
问题在于它显然仅替换了<body>
,而网站CSS会影响阻止页面。是否可以替换整个页面内容?试图取代document.body
全部抛出The provided value is not of type 'HTMLElement'.
我仍然在学习JS +扩展开发,任何建议都值得赞赏。
您遇到的问题是您要更换身体,而不是头部(或任何位于身体外部的<script>)。
要替换所有html,您要使用document.write。根据您要覆盖的方式,您可能需要调用document.open和document.close。
替换所有html的示例如下所示:
newHTML = `<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body>
<p>This is a very simple HTML document</p>
<p>It only has two paragraphs</p>
</body>
</html>`
document.open()
document.write(newHTML)
document.close()
使用Chrome开发者工具(应该是选项>更多工具>开发者工具),我们可以导航到控制台并获取内容
-> document.documentElement.outerHTML
<- html
<html><head>
<title>
A Simple HTML Document
</title>
</head>
<body>
<p>This is a very simple HTML document</p>
<p>It only has two paragraphs</p>
</body></html>"
这个jsfiddle示例显示了它的外观,并替换了CSS背景。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句