Utilizing Chrome Context Script plugin to monitor page changes: A step-by-step guide

Currently, I am in the process of creating a basic Chrome extension with the purpose of removing specific DOM elements from a particular website.

In my manifest.json file:

{ 
  "name": "example", 
  "version": "1.0",
  "description": "example description", 
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["myscript.js"]
    }
  ],
  "permissions": [
  "tabs", 
  "http://*/*"
    ]
}

In my myscript.js file:

window.onload = start;

function start()
{
    var ads = document.getElementById("left_ads");
    ads.parentNode.removeChild(ads);
    alert("example message");
}

Currently, my script successfully removes the div id="left_ads" when I initially load a target page. However, if I navigate to another page with a similar div id="left_ads", the script fails to take effect. I suspect that I may need to utilize a different event other than window.onload(). Can anyone suggest an alternative event that I should use?

Answer №1

After some experimentation, I have successfully resolved this issue by utilizing a background HTML file to enhance the plugin. Here is how the plugin code appears now:

manifest.json:

{ 
  "name": "bla", 
  "version": "1.0", 
  "description": "bla", 
  "background_page": "background.html",
  "permissions": [
  "tabs", 
  "http://*/*"
    ]
}

background.html:

<html>
  <script>
    chrome.tabs.onUpdated.addListener(start);

    function start(tabID, changeInfo, tab)
    {
        chrome.tabs.executeScript(null, { file: "myscript.js"   })

    }

  </script>
</html>

myscript.js:

var ads = document.getElementById("left_ads");
ads.parentNode.removeChild(ads);

The solution works flawlessly on all pages.

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

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

Assigning specific class names to elements within an array using JavaScript

Currently, I'm attempting to assign a unique className to option elements within a select element by utilizing a conditional if statement. The goal is to apply one class name to the first half of the array and a different class name to the second half ...

I'm looking to dynamically populate a DropDown list by utilizing Ajax in conjunction with a C# method. Can

Greetings, I have developed a C# method which looks like this: [WebMethod] protected static void populateDropdown(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc) { int data = 0; string query; dat ...

Use include files to wrap content in a div tag

I have a webpage index.html with the following JavaScript scripts: <script type="text/javascript> $(document).ready(function() { $('a.link').click(function() {var url = $(this).attr('href'); $('#content'). ...

Encountering an error stating 'ReadableStream is not defined' while attempting to log in using Discord on the NextAuth application

While attempting to set up a Discord sign-in page to test NextAuth on my website, I encountered the error ReferenceError: ReadableStream is not defined. After examining the stack trace, it seems to be related to how my packages are configured, but I' ...

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click eve ...

Problem with the property `className` not adding correctly on `$scope.eventSource`

Currently, I am utilizing the AngularJS directive to integrate the Arshaw FullCalendar. However, I am encountering an issue where the className specified in $scope.eventSource is not appearing on the event object. Here is a snippet of my code: $scope.even ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

What are the benefits and drawbacks of combining Jquery UI with AngularJS in web development?

Currently, I am developing a Web application and considering integrating JqueryUI and AngularJS into my ASP.NET MVC project. Is this the best decision for my project? Are there any recommended Databinding libraries that can be used with JQuery UI? Please ...

Unraveling encoded characters in URLs using Node.js

When I try to send a cookie back using res.cookie(JSON.stringify({bar: "baz"}), the value that I get in return is %7B%22bar%22%3A%22baz%22%7D. How can I decode this in a Javascript setting like node.js? ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

Help setting up Angular ng-class is needed

Hey there, I'm currently attempting to change the background color of my CSS based on the value of ng-class (true or false). Can someone help me out with this? <div id="home"> Summoner <div id="in ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

What is the best way to incorporate JavaScript code as React syntax?

For my project, I am using the OpenLayers API Map. I'm unsure of the correct way to incorporate JavaScript code in React or vice versa. Here is an answer on how to use markers in the map, but I am struggling to implement it in my current code since I ...

Visualizing Data with d3.js Radar Charts Featuring Image Labels

After following a tutorial on creating a d3.js radar chart from http://bl.ocks.org/nbremer/21746a9668ffdf6d8242, I attempted to customize it by adding images to the labels. However, I encountered an issue with aligning the images properly. You can view my ...

Wind - Best practices for managing the status of multiple entities within a single display prior to executing the save changes function

In my system, there are three main entities: Project, Attachment, and Messages. A project can have multiple attachments and messages associated with it. The issue arises on the project detail view, where I display the project's messages and any attac ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...