Issue: Unhandled TypeError: Problem detected when calling storage.set(object items, optional function callback) in a Chrome Extension

Attempting to create my first Chrome extension, focusing on blocking access to specific websites like Facebook or Instagram. Using code to close tabs if the blocked sites are accessed.

In a separate HTML file, providing users with two radio button options to block either Facebook or Instagram.

Encountering an error on line 9 when attempting to load the extension in Chrome:

"Uncaught TypeError: Error in invocation of storage.set(object items, optional function callback): No matching signature."

Struggling to comprehend explanations found online due to being new to coding. Seeking assistance to proceed forward!


CODE:

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;
            }
        });
    }

Answer №1

The issue arises from incorrectly specified parameters.

According to the documentation, only two parameters are allowed - one as an object and the other as an optional function. However, in your code, you have passed three parameters with the second one being the result of chrome.webRequest.onBeforeRequest.addListener, which does not return anything as mentioned in the documentation. This results in passing `object`, `undefined`, and `function` instead of `object`, `function`.

Resolution

To fix this error, rearrange the order of chrome.webRequest.onBeforeRequest.addListener relative to 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']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle Button Control

In my PHP file, I have a submit button for the form coded like this: <input type="submit" name="submit" value="submit" disabled="true" /> Next, I initiate an asynchronous request using a request object, document.getElementById("username").onblur= ...

Revising text for real-time editing

Most of us are familiar with the functionality on StackOverFlow that allows you to preview your text before posting a question. I'm interested in implementing a similar feature on my website and am looking for some guidance on how to get started. I ...

Executing asynchronous jQuery AJAX requests using the async/await syntax

Currently, I have a situation where I am using 3 ajax call methods in succession. However, there needs to be a delay between the second and third ajax calls. Initially, I used "async:false" in the second ajax call and everything worked smoothly. But later ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

What benefits does JavaScript offer with the strategy of storing functions within variables?

Lately I've come across some code where functions are being stored inside variables and then called in the typical way. For example: var myFunctionName = function() { Code Here... } myFunctionName(); I'm aware that there may be numerous b ...

The process of querying two MySQL tables simultaneously in a Node.js environment using Express

My goal is to display both the article and comments when a user clicks on a post. However, I've encountered an issue where only the post loads without the accompanying comments. Here is the code snippet that I've been working with: router.get(&a ...

Ways to verify multiple radio groups to ensure none have been left unchecked

https://i.sstatic.net/EoE1A.png Is there a more elegant solution to check if either "salad" or "side dish" is left unchecked after submission? I currently have a working approach, but it feels overly complex for such a simple task. This is my current me ...

What is the method for sending these variables via POST?

The code snippet referred to as New script is designed to produce two integer variables anchor and signed. I am interested in replacing the Old script with the New script, but there are significant differences between them. Inquiry How can I send/post t ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Tips for positioning a box on top of a map in a floating manner

I am trying to figure out how to position the div with class box on top of the map in this jsbin. Can someone help me achieve this? Below is the CSS code I have for styling the box and body. body { font-family: "Helvetica Neue", Helvetica, sans-serif; ...

Toggle the visibility of a component by clicking on a specific title within a table, dependent on the column title in Angular 9

Currently, I am developing an Angular application focused on creating a COVID-19 tracking app. In this project, I have designed 2 components - Component A displays a list of all states, while Component B lists all districts within a particular state. To ...

Guide to interpreting an Angular expression using traditional JavaScript conventions

I have encountered an issue with the Angular app that I am currently working on. It needs to retrieve the Google Analytics ID from Angular in order to pass it to ga('create', 'UA-XXXXX-Y') using standard JavaScript in my index.html. &l ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

The execution of a link in Firefox is blocked only when an active div is shown

The code includes an <a href> element that wraps around two div elements. One of the divs is only displayed when the link is clicked, and it appears above the other div. This setup serves as a visual feedback mechanism for user interaction. To see a ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Angular Material 2 with Customized Moment.js Formatting

Is there a way to display the year, month, day, hours, minutes, and seconds in the input field of my material datepicker? I have successfully customized the parse() and format() methods in my own DateAdapter using native JavaScript objects. Howe ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...

Styling a rectangle in p5.js: Tips and tricks

In my p5.js code, I created a rectangle using rect(): rect(10, 10, 10, 10); Now, I want to add some style to it with a box-shadow effect: box-shadow: 20px 20px 50px #00d2c6, -30px -30px 60px #00ffff; However, when I tried to apply the style using the doc ...