【问题标题】:chrome.webrequest in a event listener function事件侦听器函数中的 chrome.webrequest
【发布时间】:2015-03-01 20:21:23
【问题描述】:

当您单击扩展程序中的开始按钮时,我正在尝试启动 webrequest 侦听器。但是,它不起作用。当我在函数之外添加 webrequest 侦听器时,它可以工作。这是我的代码:

ma​​nifest.json

{
  "manifest_version": 2,

  "name": "SimplyFocused",
  "description": "This extension will stop procrastination.",
  "version": "1.0",
  "options_page": "options.html",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Simply Focused</title>
    <link rel="stylesheet" href="bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="background.js"></script>
    <script src="popup.js"></script>
  </head>
  <body id="popup">
      <button class="btn btn-default" id="start">Start</button>
  </body>
</html>

popup.js

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('start').addEventListener('click', startBlock);
    });

background.js

 if (localStorage.getItem("blocked") == null) {
        localStorage.setItem("blocked", JSON.stringify([]));
    }

    function startBlock() {
        var blockedSites = ["*://www.yahoo.com/*"];
        console.log(blockedSites);
        chrome.webRequest.onBeforeRequest.addListener(
            function(details){console.log(details); return {cancel: true};},
            {urls: ["*://www.yahoo.com/*"]},
            ["blocking"]);
    }

    // chrome.webRequest.onBeforeRequest.addListener(
    //  function(details){console.log(details); return {cancel: true};},
    //  {urls: ["*://www.yahoo.com/*"]},
    //  ["blocking"]);

当我取消注释 background.js 中的注释部分时,阻止工作。我猜这与 webrequest 甚至没有基础有关,但我不确定。谢谢!

【问题讨论】:

    标签: javascript google-chrome webrequest event-listener


    【解决方案1】:

    Popup 和 background 不是同一个页面。尝试使用chrome.extension.getBackgroundPage()方法访问后台的startBlock函数:

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('start').addEventListener('click', function() {
            chrome.extension.getBackgroundPage().startBlock();
        });
    });
    

    【讨论】:

    • 非常感谢!这样可行。我是 javascript 新手,我的原始代码会发生什么?因为它正在记录被阻止的站点,但没有添加侦听器。
    • 将弹出窗口和背景视为基本不同的页面。所以弹出“窗口”中没有函数startBlock。
    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多