Error: Uncaught TypeError: Error in invocation of storage.set(object items, optional function callback) Chrome Extension

Error: Uncaught TypeError: Error in invocation of storage.set(object items, optional function callback) Chrome Extension

我第一次练习如何构建 chrome 扩展(我对此很陌生)。扩展的目的是阻止用户访问某些网站,如 Facebook 或 Instagram。到目前为止,我使用的代码会在他们尝试访问它并阻止该网站时关闭该选项卡。

在单独的 HTML 文件中,我有 2 个选项可供用户选择 - 阻止 Facebook 或 Instagram(作为 2 个单选按钮)。

第 9 行,当我尝试将其放入 Chrome:

时出现此错误

“未捕获类型错误:调用 storage.set(对象项,可选函数回调)时出错:没有匹配的签名。”

我已经阅读了其他网站对此错误的解释,但老实说,我不了解它们,因为我是编码新手。非常感谢任何有关如何前进的帮助!


代码:

document.addEventListener('DOMContentLoaded', function() {
selectCurrentValues();
let saveButton = document.getElementById('save');
if(saveButton) {
    saveButton.addEventListener('click', function() {

    let closingMethodRadios = document.getElementsByName('blockingMethod');
    if(closingMethodRadios[0].checked){
        chrome.storage.sync.set({'blockingMethod': "close_tab"},
        chrome.webRequest.onBeforeRequest.addListener(
            function(details) { return { cancel: true }},
            { urls: ["*://*.facebook.com/*"]},
            ["blocking"]
        ),

        function() {
            console.log('Closing tab set.');
        });
    }
    else if(closingMethodRadios[1].checked){
        chrome.storage.sync.set({'blockingMethod': "close_tab"}, 
        chrome.webRequest.onBeforeRequest.addListener(
            function(details) { return { cancel: true }},
            { urls: ["*://*.instagram.com/*"]},
            ["blocking"]
        ),  
        
        function() {
            console.log('Closing tab set.');
            });
        }
    });
}});

function selectCurrentValues(){
chrome.storage.sync.get('blockingMethod', function (data){
    switch(data.blockingMethod){
        case "close_tab":
            document.getElementById("close_tab").checked = true;
            break;
        case "clear_tab":
            document.getElementById("clear_tab").checked = true;
            break;
            }
        });
    }

该错误表示指定了错误的参数。

文档 says two parameters can be specified, one is object and another is an optional function. Your code however passes three parameters, the second being the result of calling chrome.webRequest.onBeforeRequest.addListener, which doesn't return anything as we can see in the documentation 因此您的代码通过 object, undefined, function 而不是 object, function

解决方案

将 chrome.webRequest.onBeforeRequest.addListener 移动到 chrome.storage.sync.set 之前或之后。

chrome.storage.sync.set({'blockingMethod': 'close_tab'},
  () => console.log('Closing tab set.'));

chrome.webRequest.onBeforeRequest.addListener(
  () => ({cancel: true}),
  {
    urls: ['*://*.facebook.com/*'],
    types: ['main_frame'],
  },
  ['blocking']);