当您单击扩展程序中的开始按钮时,我正在尝试启动webrequest侦听器。但是,它不起作用。当我在函数外部添加webrequest侦听器时,它可以正常工作。这是我的代码:
的manifest.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有关甚至没有基础,但我不确定。谢谢!
答案 0 :(得分:0)
弹出窗口和背景不是同一页面。尝试使用chrome.extension.getBackgroundPage()
方法访问后台startBlock
函数:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('start').addEventListener('click', function() {
chrome.extension.getBackgroundPage().startBlock();
});
});