【发布时间】:2016-11-08 02:09:01
【问题描述】:
我正在尝试制作一个简单的 Chrome 扩展程序,通过将其替换为短文本来“阻止”网站 Reddit 的内容。这是我目前所拥有的:
manifest.json
{
"manifest_version": 2,
"name": "BlockIt",
"description": "Block Reddit, increase productivity!",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_title": "BlockIt"
},
"permissions": [
"storage", "tabs",
"http://www.reddit.com/*"
],
"content_scripts": [
{
"matches": [ "*://reddit.com/*" ],
"js": ["content-script.js"]
}
]
}
popup.html
<!doctype html>
<html>
<head>
<style>
body {
font-family: Verdana, Arial, Helvetica, Tahoma, sans-serif;
background-color:#EFF7FF;
margin: 5px 5px 5px 5px;
width: 110px;
height: 100%;
text-align:center;
}
</style>
<!--Scripts-->
<script src="popup.js"></script>
</head>
<body>
<h2>BlockIt!</h2>
<div id="en"><label for="enable">Enable BlockIt</label> <input id="enable" type="checkbox" style="vertical-align:middle; position:relative; bottom: 1px;"/>
</div>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#enable').addEventListener('change', changeHandler);
});
function changeHandler() {
if (enable.checked) {
chrome.storage.sync.set({ 'enable': true }, function () { });
}
}
content-script.js
var content = document.getElementsByTagName("body");
var text = "BlockIt enabled (to disable, click on the icon).";
//TODO: replace content with text
我现在有两个主要问题:我不知道我应该如何修改网页内容并将其替换为上面的text,我不知道如何注入@ 987654327@ 选中popup.html 中的复选框时。我该如何解决这个问题?
编辑:我对我的代码进行了以下更改:
content-script.js
chrome.storage.sync.get({ enable: false }, items=> {
if (items.enable) {
document.body.textContent = "BlockIt enabled (to disable, click on the icon).";
}
});
它成功改变了网页的正文,但现在的问题是popup.html的内容也变成了相同的文本。似乎是什么问题?
编辑 2:
我在popup.html 中删除了content-scrip.js。复选框的状态仍然不存在。这似乎是一个简单的解决方案,但我似乎无法修复它。任何帮助将不胜感激。
【问题讨论】:
-
这确实是两个截然不同的问题。首先,我们需要知道您想要替换什么。您要替换整个
<body>(例如document.body.textcontent=text;)、整个<document>等吗?将webRequests屏蔽到redit.com可能更容易。 -
@Makyen 我想替换输入
body。阻止webRequests时是否可以显示自定义消息? -
是的,您可以显示阻止
webRequest的自定义消息。但是,您这样做的方式是不同的。您可以将请求重定向到您的扩展程序中包含阻止消息的 HTML 文件。 -
Arg... 我的第一条评论中有错字。应该是
document.body.textContent=text;(注意textContent中的大写C)。 -
仅供参考:从 Stack Overflow 的角度来看,您最近的两个编辑都应该是 new Questions(您可以在新问题中找到指向此问题的链接以获取上下文)。此外,当您对问题进行编辑时,没有人会收到通知。如果你想通知特定的人,你需要在他们写的问题或答案上发表评论,或者添加一个评论,其中包括他们的用户名,前面有一个
@(例如@Makyen,对我来说)。您只能通过@/comment 指定一个人,但您评论的问题/答案的原始发布者始终会收到通知。
标签: javascript html google-chrome google-chrome-extension