Error message in Chrome extension: Unable to execute the 'appendChild' method on a null object while attempting to create an overlay div

I attempted to create a simple overlay div using a Chrome extension, and it usually works fine. However, I encountered an error on a few specific sites such as: http://en.wikipedia.org/wiki/Main_Page when trying to add the div.

Below is the code I used:

var s = document.createElement('script');
s.src = chrome.extension.getURL('script_inpage.js');
s.onload = function() {
    s.parentNode.removeChild(s);
};

try{
 console.log("appendChild START");
    (document.head||document.documentElement||document.body).appendChild(s);
 console.log("appendChild DONE");
}catch(e){
  console.log("exception in appendChild");
}  

Here is script_inpage.js:

try{
    var buttonnode= document.createElement('input');
    buttonnode.setAttribute('type','button');
    buttonnode.setAttribute('id','test_btn');
    buttonnode.setAttribute('value','Test!');


    var div_bottom = document.createElement("div");
    div_bottom.id = "div_bottom";
    div_bottom.style.width = "300px";
    div_bottom.style.height = "20px";
    div_bottom.style.background = "#999";
    div_bottom.style.position="fixed";
    div_bottom.style.bottom="0";
    div_bottom.style.right="0";
    div_bottom.style.zIndex="9999"
    div_bottom.innerHTML = "Hello from div";
    div_bottom.appendChild(buttonnode);
    document.body.appendChild(div_bottom);
}
catch(e){
  console.log("script in page exception in appendChild"+e);
  alert(e);
} 

And here is the content of manifest.json:

{
   "background": {
      "page": "background.html" 
   },
   "content_scripts": [
    {
      "matches": ["<all_urls>"],       
      "js": ["contentscript.js"],
      "run_at": "document_end",
      "all_frames": true
    }
   ],
   "web_accessible_resources": [
    "script_inpage.js"
   ],
   "browser_action": {
      "default_icon": "icon19.png",
      "default_popup": "popup.html",
      "default_title": "Simple test"
   },
   "content_security_policy": "script-src 'self'; media-src *; object-src 'self'",
   "description": "Simple test.",
   "icons": {
      "128": "icon128.png",
      "16": "icon16.png",
      "32": "icon32.png",
      "48": "icon48.png"
   },

   "manifest_version": 2,
   "minimum_chrome_version": "20",
   "name": "Simple test",
   "permissions": [ 
        "unlimitedStorage",
        "http://*/",
        "<all_urls>",
        "tabs"
   ],

   "version": "2.6"
}

Answer №1

Functioning properly for me when using the following code along with http://en.wikipedia.org/wiki/Main_Page

manifest.json

{

   "content_scripts": [
    {
      "matches": ["<all_urls>"],       
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true
    }
   ],
   "web_accessible_resources": [
    "scripts.js"
   ],
   "browser_action": {
      "default_title": "Simple test"
   },
   "content_security_policy": "script-src 'self'; media-src *; object-src 'self'",
   "description": "Simple test.",


   "manifest_version": 2,
   "minimum_chrome_version": "20",
   "name": "Simple test",
   "permissions": [ 
        "unlimitedStorage",
        "http://*/",
        "<all_urls>",
        "tabs"
   ],

   "version": "2.6"
}

scripts.js

try{
    var buttonnode= document.createElement('input');
    buttonnode.setAttribute('type','button');
    buttonnode.setAttribute('id','test_btn');
    buttonnode.setAttribute('value','Test!');


    var div_bottom = document.createElement("div");
    div_bottom.id = "div_bottom";
    div_bottom.style.width = "300px";
    div_bottom.style.height = "20px";
    div_bottom.style.background = "#999";
    div_bottom.style.position="fixed";
    div_bottom.style.bottom="0";
    div_bottom.style.right="0";
    div_bottom.style.zIndex="9999"
    div_bottom.innerHTML = "Hello from div";
    div_bottom.appendChild(buttonnode);
    document.body.appendChild(div_bottom);
}
catch(e){
  console.log("Encountered an exception while executing script on page: "+e);
  alert(e);
} 

content.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('scripts.js');
s.onload = function() {
    s.parentNode.removeChild(s);
};

try{
 console.log("Starting to appendChild");
    (document.head||document.documentElement||document.body).appendChild(s);
 console.log("appendChild COMPLETED");
}catch(e){
  console.log("Exception occurred in appendChild");
} 

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

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Retrieving and splitting several values using GetElementById method after a specific character

My knowledge of JavaScript is limited, but I'm facing a problem with passing two values using the getElementID method. Is it possible to use this method twice as shown below or should I consider using another GetElementBy/GetElementsBy method to achie ...

Transform CSV data into JSON format to generate an empty JSON file

I've been attempting to convert a CSV file to JSON using the convert-csv-to-json package from npm. Although I can successfully retrieve the CSV file from the specified URL and create a 'data.csv' file, the resulting JSON file is only an empt ...

Having trouble with my Express.js logout route not redirecting, how can I troubleshoot and resolve it?

The issue with the logout route not working persists even when attempting to use another route, as it fails to render or redirect to that specific route. However, the console.log("am clicked"); function works perfectly fine. const express = require('e ...

The module at 'D:Education odemonin odemon.js' could not be located by Node

I am just starting out with NodeJS My setup is on Windows 11 64 Bit system. Node, Nodemon (Global installation), and NPM are all properly installed and operational. However, when I execute the command npm run server It results in the following erro ...

What is the best way to make a Firestore request that relies on the initial Firebase response in Next.js?

Is there a way to perform a second cloud Firestore query using the uid obtained in the first query, without the second query executing before receiving the response from the first one? Here's my code: var {data} = useSWR('/api/report', fet ...

Activate Bootstrap - navigate to a specific tab and scroll to a designated anchor upon link click

My goal is to switch to another tab and scroll to a specific part of the page after clicking on a link inside a tab. Unfortunately, although I have successfully switched tabs, I am unable to scroll down to the anchor point. I would greatly appreciate any ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

Exploring the intricacies of logic through the interactive features of .hover and .click in tandem with Raphael

My goal is to create a hover effect and a click state for a specific area on a map. At present, I want one color to appear when hovering, and another color to display when clicked. Ideally, I'd like the click color to remain even after the user moves ...

Adding information into sqlite from a json document

There seems to be an issue here, I'm unable to make an insertion: $.getJSON('file.json', function(data) { tx.executeSql("INSERT INTO table (DATE, LIB, BID) VALUES("+data.date+","+data.Lib+","+data.BID+")"); }); ...

Javascript is currently facing issues with callbacks not functioning properly in an asynchronous manner

Attempting to execute one function after another in my discord.js code. Here is what I have: function1(function2) async function function1(callback) { var guild = client.guilds.cache.get(config.Server); let channels = guild.channels; fo ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

Guidance on executing a JavaScript function from PHP or HTML

Although this may appear simple to some, I am relatively new to this and have been searching everywhere. I currently have a javascript function. mkfile : function(fm) { I am attempting to run this from an on-click event. Any suggestions? I apologize fo ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

How come my ajax function is not processing when the form is submitted?

Having an issue with validating a form where I need to check if a username is available before submission. Although all functions, including the PHP script for checking the username, are working properly, I'm unable to prevent the form from submitting ...

Guide for adding a record to sqlexpress with javascript on aspx pages

Does anyone know how to use JavaScript in an ASPX file to insert a record into SQLExpress? ...

Retrieve the class using a text string and then obtain the subsequent string

I am searching for the first class containing the text "Routed:" and then I want to retrieve the following string. I attempted to utilize document.querySelector, but I'm uncertain if this is the correct approach. <td class="msvb2">Routed:</t ...

Steps to design a unique input radio button with embedded attributes

In my current project, I am utilizing react styled components for styling. One issue that I have encountered is with the text placement within a box and the need to style it differently when checked. What have I attempted so far? I created an outer div a ...