使用webrequest API的Chrome扩展程序块

时间:2017-12-06 06:10:38

标签: javascript google-chrome-extension

您好我正在使用Chrome扩展程序来阻止除用户选择的设置列表之外的所有网页。我没有太多关于Chrome Extensions或JavaScript的经验。

目标是在用户设置弹出窗口中的时间并单击提交时运行阻止脚本。因此,当用户在弹出窗口中提交时,我试图阻止Web请求一段时间,直到警报API创建的警报被触发为止。

现在我忽略了白名单,只是试图让webrequest阻止正常工作。目前,似乎代码仅在检查弹出窗口时运行。我怀疑该脚本只在弹出窗口打开时才能正常运行。我认为问题是架构,因为我从background.js运行它。任何有关更好的处理方式的指导都会很棒。

以下是我的代码的重要部分:

的manifest.json

  "browser_action": 
  {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Start being productive!"
  },


  "permissions": ["webRequest", "webRequestBlocking",
                  "https://www.google.com/*", 
                  "alarms",
                  "activeTab"],

  "background": 
  {
    "scripts": ["whitelist.js", "background.js"]
  }

popup.html

 <body>
    <h1>Productivity Time</h1>
    <div id="container">
      <form id="whitelist">
        <input type="text" class="white_list" id="sites" autocomplete="off" placeholder="Enter URLs of websites to be whitelisted"></input>
        <input type="submit" value="Add"></input>
      </form>
    </div>
    <br></br>  
    <div id="container">
        <form id="timer">
          <span>Set Timer: </span>
          <input type="number" id="minutes" min="0" step="1" max="45">Minutes</input>
          <input type="submit" value="Start!"></input>
        </form>
    </div>

    <script src="whitelist.js"></script>
    <script src="background.js"></script>

  </body>

background.js

// Event handler to make alarm and start blocking
document.getElementById('timer').addEventListener('submit', blockingScript);

function blockingScript(event) {
    // Clear previous alarms
    chrome.alarms.clearAll();

    // Check that user selected a time
    if (document.getElementById('minutes').value == '')
    {
        alert("Please set time");
    }

    // Alarm will fire when user set amount of time has elapsed
    let delay = parseFloat(document.getElementById('minutes').value);
    alert(delay);
    chrome.alarms.create("alarm", {delayInMinutes: delay});

    // Block URLs
    chrome.webRequest.onBeforeRequest.addListener(
        function(details) { return {cancel: true}; },
            {urls: ["https://www.google.com/*"]},
            ["blocking"]);
}

0 个答案:

没有答案