Chrome扩展程序:修改网页的内容 [英] Chrome extension: Modifying the content of a webpage

查看:1292
本文介绍了Chrome扩展程序:修改网页的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的Chrome扩展程序,在该扩展程序中,我将用简短的文字替换它,以阻止Reddit网站的内容。这是我迄今为止:

manifest.json

  {
manifest_version:2,

name:BlockIt,
description:阻止Reddit,提高生产力! ,
version:1.0,

browser_action:{
default_icon:icon.png,
default_title:BlockIt
},

权限:[
存储,标签,
http://www.reddit.com/*$ b $ b,

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;
背景颜色:#EFF7FF;
margin:5px 5px 5px 5px;
width:110px;
身高:100%;
text-align:center;
}
< / style>
<! - 脚本 - >
< script src =popup.js>< / script>
< / head>
< body>
< h2> BlockIt!< / h2>
< div id =en>< label for =enable>启用BlockIt< / label> < input id =enabletype =checkboxstyle =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(禁用,点击图标)。;
// TODO:用文本替换内容

现在我有两个主要问题:我不确定如何修改网页内容并用上面的文本替换它,我不知道如何注入<$当选中 popup.html 中的复选框时,c $ c> content-script.js 。



编辑:我对我的代码进行了以下更改:



content-script.js

  chrome.storage.sync .get({enable:false},items => {
if(items.enable){
document.body.textContent =BlockIt enabled(禁用,点击图标)。
}
});

它成功更改了网页的正文,但现在的问题是 popup.html 也会更改为相同的文本。什么似乎是问题?

编辑2
我已经删除了 content-scrip。 js 位于 popup.html 中。复选框的状态仍然不会持续。这似乎是这样一个简单的解决方案,但我似乎无法修复它。任何帮助将不胜感激。

解决方案

使用 webRequest API 请求重定向。



假设您有一个显示内容的页面 blocked.html



然后,再次假设扩展状态存储在 chrome.storage.sync 中,就像在Mayken的答案中一样。您需要同步缓存值,因为重定向必须是同步的。

  //后台脚本
var启用;

函数cacheEnabled(){
chrome.storage.sync.get({enable:false},data => {
enabled = data.enable;
});
}

cacheEnabled();
chrome.storage.onChanged.addListener(cacheEnabled);

chrome.webRequest.onBeforeRequest.addListener(
details => {
if(enabled){
return {redirectUrl:chrome.runtime.getURL(blocked .html)};
}
},
{
网址:[*://*.reddit.com/*],
类型: [main_frame,sub_frame]
},
[blocking]
);

这要求权限webRequest,webRequestBlocking,*:/ / *。reddit.com / *



注意:这不是最佳解决方案:注册/取消注册监听器更好取决于启用,而不是在侦听器中检查它(应该尽可能快)。这留作练习。


I'm trying to make a simple Chrome Extension where I will 'block' the content of the website Reddit by replacing it with a short text. This is what I have so far:

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

I'm having two major issues right now: I'm not sure how I should go about in modifying the content of the webpage and replace it with the text above, and I'm not sure how to inject content-script.js when the checkbox in popup.html is checked. How do I go about in approaching this?

Edit: I've made the following change to my code:

content-script.js

chrome.storage.sync.get({ enable: false }, items=> {
    if (items.enable) {
        document.body.textContent = "BlockIt enabled (to disable, click on the icon).";
    }
});

It successfully changes the body of the webpage, but the issue now is that the content of popup.html changes to the same text as well. What seems to be the problem?

Edit 2: I've removed content-scrip.js in popup.html. The state of the checkbox still doesn't persist. It seems like such a simple solution but I can't seem to fix it. Any help would be appreciated.

解决方案

It's likely to be much more resource-efficient to block using webRequest API request redirection.

Let's say you have a page blocked.html that is shown in place of content.

Then, again, suppose that the extension state is stored in chrome.storage.sync, as in Mayken's answer. You'll need a synchronous cache of the value, because redirect must be synchronous.

// Background script
var enabled;

function cacheEnabled() {
  chrome.storage.sync.get({enable: false}, data => {
    enabled = data.enable;
  });
}

cacheEnabled();
chrome.storage.onChanged.addListener(cacheEnabled);

chrome.webRequest.onBeforeRequest.addListener(
  details => {
    if (enabled) {
      return { redirectUrl: chrome.runtime.getURL("blocked.html") };
    }
  },
  {
    urls: ["*://*.reddit.com/*"],
    types: ["main_frame", "sub_frame"]
  },
  ["blocking"]
);

This requires permissions "webRequest", "webRequestBlocking", "*://*.reddit.com/*".

Note: This is not an optimal solution: it's even better to register/unregister the listener depending on enabled rather than check it inside the listener (which should be as fast as possible). This is left as an exercise.

这篇关于Chrome扩展程序:修改网页的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆