unable to load variables in google extension due to technical difficulties

I'm encountering an error even though I've already loaded the DOM. I have no idea how to fix this issue and I've been sitting here for hours trying to troubleshoot. The error message I'm getting is:

btncheck.js:10 Uncaught TypeError: Cannot read property 'checked' of null
    at save_options (btncheck.js:10)
    at btncheck.js:28

Below is my popup.js code snippet:

(function() {
  if (window.addEventListener) {
    window.addEventListener('DOMContentLoaded', domReady, false);
  } else {
    window.attachEvent('onload', domReady);
  }
}());

function domReady() {
  onoffbtn = document.getElementById('onoffbtn').checked
}


function save_options() {
  chrome.storage.sync.set({
    onoffbtn: onoffbtn
  }, function() {
    setTimeout(function() {

    }, 750);
  });
}

function restore_options() {
  chrome.storage.sync.get({
    onoffbtn: true
  }, function(items) {
    document.getElementById('onoffbtn').checked = items.onoffbtn;
  });
}
document.addEventListener('DOMContentLoaded', restore_options);
setInterval(function() {
  save_options();
}, 1000);

// Additional code snippets...

This is a shortened version of my manifest.json file:

{
"name": "Hello Extensions",
"description" : "Base Level Extension",
"version": "1.0",
"manifest_version": 2,
"permissions": ["tabs", 
    "*://*.beta.esportal.se/*", 
    // Other permissions...
],
"background" : {
    // Background script configuration...
},
"content_scripts":[
    {
    // Content scripts configuration...
}
],
"browser_action": {
  "default_popup": "startpage.html"
}

}

This is a section of my background.js file:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {

    chrome.tabs.executeScript({
        file: 'popup.js'
    });
   }
});

And finally, the content.js file contains the following code:

chrome.runtime.onMessage.addListener(gotMessage);

function gotMessage(message,sender,sendResponse){
    if(message == 1){
        // Modify the page based on message value being 1
        console.log(1);
    }else{
        console.log(0);
    }
}

Answer №1

It is important to ensure the element's existence before attempting to access its properties.

function save_options() {
  let onoffbtn = document.getElementById('onoffbtn');
  if (onoffbtn) {
    chrome.storage.sync.set({
      onoffbtn: onoffbtn.value
    }, function() {
      setTimeout(function() {

      }, 750);
    });
  }
}

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

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

The vanishing act: Semantic UI menu disappears when you click

My objective is to create a persistent left-side menu using Semantic-UI. I want to implement two different states for the menu - one with text for each item and another with an image for each item. However, I am facing some challenges that have me complete ...

Occasionally, AJAX requests may not always be in the correct sequence

I'm struggling with the POST and GET requests. Everything seems to be in order on my server side until I send the data, but then things get jumbled up on the client side. For instance, the data should be received in reverse order as shown below: Data ...

Select dropdown in AngularJS for Date formatting

After retrieving json data from a web API, I found that it contains a series of datetimes. My goal is to select a specific datetime from a dropdown list. While I can populate the list without any issues, the formatting appears to be incorrect and I'm ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

Combining Objects in an Array using Node.js: A Step-by-Step Guide

I am working with Node.js and have 3 different sets of data. The first set contains: [ { "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3", "dailyData":159392.235451, "dailyDataInUSC":255.28 ...

What could be causing the child of an ES6 imported object to return as undefined?

Here is the code snippet I am working with: import * as _routes from '../../routes' console.log('parent:', _routes) console.log('child:', _routes.breadcrumb) This code produces the following output: https://i.stack.imgur.co ...

Main navigation category as parent and secondary category as a child menu in WordPress

Hello there, I am looking to create a navigation menu with parent categories displayed horizontally and child categories as corresponding submenus. For example, The parent categories would be Apple, Orange, and Mango Under Apple, we would have apple1, ...

Change the value in Vue through a single action (swapping out buttons)

I created a custom component that allows users to add points only once by clicking a button. I want to add an undo option to decrease the point value by 1 after it has been added. When a point is added, I'd like the button to change color to red and d ...

AngularJS controller containing a nested app

Is there a way to implement this structure using AnglularJS? <body ng-app="mainBodyAppWrapper"> <div ng-controller = "mainBodyController"> <div ng-app="myApp"> <div ng-controller="controller3"> ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

When I switch to a different navigation system, the css class gets removed

Let me clarify what I am looking for: Upon entering the index.php page, LINK_1 button is active. When I switch to LINK_2, it becomes active. I have only one index.php page where I include parts of external pages using PHP. Page_1 https://i.sstatic.net/Yv ...

Troubleshooting: AngularJS Form Submission Failure

As a novice in Angular and not a JavaScript expert, I am facing challenges with form submission. My task involves loading movie showtimes from an http API and using ng-repeat to display them within a page container. The REST API requires a zipcode input, w ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

Using JavaScript to Access PHP Files

Would like to understand the process of calling a php file (test.php) from either "x:" or "y:" in the code below. var example1 = { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], name: 'Most read', ...

Is combining Nuxt 3 with WP REST API, Pinia, and local storage an effective approach for user authentication?

My current project involves utilizing NUXT 3 for the frontend and integrating Wordpress as the backend. The data is transmitted from the backend to the frontend through the REST API. The application functions as a content management system (CMS), with all ...

Remove attributes from a collection of objects

Here is an array of objects: let array = [{ firstName: "John", lastName : "Doe", id:5566, weight: 70 },{ firstName: "Francis", lastName : "Max", id:5567, weight: 85 }]; I am looking to remove the properties "lastName" and "weight" for all obj ...

What could be the reason for the three.js scene failing to render in my Svelte application?

Scene.svelte <!-- Start by binding a container, then add the renderer to this container onMount --> <script> import { onMount } from 'svelte'; import * as THREE from 'three'; let container; onMount(async () = ...

Tips for adding page numbers to a PDF created from HTML using wkhtmltopdf

Our response: We currently utilize wkhtmltopdf for generating PDFs from a specified html template. A brief overview: We incorporate Sulu CMF in constructing our backend, which is built on Symfony2. The KnpSnappy Bundle acts as a Symfony wrapper for wkht ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...