我正在嘗試做一個簡單的Chrome擴展程序,我將通過用簡短文本替換它來「阻止」網站Reddit的內容。這是我到目前爲止有:Chrome瀏覽器擴展程序:修改網頁的內容
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() { });
}
}
內容的script.js
var content = document.getElementsByTagName("body");
var text = "BlockIt enabled (to disable, click on the icon).";
//TODO: replace content with text
我有兩個主要問題,現在:我不知道我應該如何去在修改網頁的內容,並與上述text
替換它,並且我不確定如何在popup.html
複選框被選中時注入content-script.js
。我如何着手解決這個問題?
編輯:我做了如下修改我的代碼:
內容的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
。複選框的狀態仍然不會持續。這似乎是這樣一個簡單的解決方案,但我似乎無法修復它。任何幫助,將不勝感激。
這實際上是兩個截然不同的問題。首先,我們需要知道你想要取代什麼。您是否想要替換整個'
'(例如'document.body.textcontent = text;'),整個「@Makyen我想替換輸入'body'。阻止'webRequests'時可以顯示自定義消息嗎? – coriandres
是的,您可以顯示阻止「webRequest」的自定義消息。但是,你這樣做的方式是不同的。您可以將請求重定向到您的擴展中的HTML文件,該文件將具有阻止消息。 – Makyen