What are the steps to execute background.js exclusively on certain links?

I'm currently working on a Chrome extension that is meant to automatically close tabs when they are loaded if their URLs contain specific words or strings. I initially attempted to achieve this using the matches statement in the extension's manifest.json file. Unfortunately, this approach did not yield the desired result. Here is an excerpt from my manifest.json file:

{
  "manifest_version": 2,
  "name": "Custom Tab Closer",
  "version": "1.0",
   "permissions": [
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": [
       "<all_urls>"
      ],
      "js": ["content.js"]
    }
  ],
  "background": {
          "matches": [
               "https://www.google.com/",
                "https://example.com/login"
          ],
          "scripts": ["background.js"],
          "persistent": true
  }
}

Furthermore, here is an overview of my background.js script:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {
      console.log('background script running');
      chrome.tabs.remove(tabId, function() { });
  }
})

Despite specifying that the script should only execute for pages containing URLs with 'google' and 'example.com', it seems to be running on all loaded pages. Any insights on why this might be happening?

Answer №1

Challenges:

  • In the "background" section, it's noted that "matches" cannot be used as outlined in the documentation. The background script operates on a separate hidden background page that is independent of tab activities.

  • The content script specified in your manifest.json file is set to run on all URLs. For your specific task, a content script may not be necessary at all.

Here is a multi-step Solution:

  1. Eliminate the "content_scripts" section entirely
  2. Remove the "matches" attribute from the "background" section
  3. Transition to an event page script by setting "persistent": false
  4. Include the "webNavigation" permission in your manifest.json and utilize it for detecting URL navigation events

Your updated background.js file should look like this:

chrome.webNavigation.onCompleted.addListener(closeTab, {
  url: [
    {urlPrefix: 'https://www.google.de/'},
    {urlPrefix: 'https://sghm.eu/iserv/login'},
  ]
});

function closeTab(e) {
  if (!e.frameId) {
    chrome.tabs.remove(e.tabId);
  }
}

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

Activate a CSS class on click using JavaScript

Having a bit of trouble as a beginner with this. Any help would be much appreciated. This is the code in question: HTML: <div class='zone11'> <div class='book11'> <div class='cover11'></d ...

The duplication of jQuery form with an incrementing ID is not functioning properly for the duplicated forms

My project involves creating a form with a unique ID and buttons for calculating and duplicating the form. I have successfully duplicated the form, including its sub-fields with unique IDs. However, I am facing a challenge in modifying the code to calculat ...

Converting a custom object with JodaTime attributes into JSON serialization

Upon completing an additional task that involves creating and storing an object in an ArrayList within a Singleton, I encountered an error when transitioning back to the initial Activity from the creation process. Logcat: 10-09 15:00:48.125: E/AndroidRun ...

Post Request to Express API does not produce any output

Today, I encountered an issue while trying to create a JWT authentication API in Express. When I send a POST request with Postman, it only returns {}. Below is the code for server.js: const express = require("express"); const mongoose = require("mongoos ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

There seems to be an issue with the Node JavaScript file not updating automatically

Currently facing an issue while trying to develop my first node application. The problem lies with the JavaScript file, as my CSS file is working fine which is causing confusion for me. Here is a snippet of my app.js code: var express = require("express") ...

Certain conditions in JavaScript are not executed by Internet Explorer

I am currently working on a Html file that involves XSLT. I have integrated some JavaScript code for filtering specific rows within tables. However, I have encountered an issue where certain if-cases in my JavaScript are not executing as expected when usin ...

Utilizing jQuery to manage asynchronous tasks, such as executing AJAX requests, handling promises, and using deferred

Exploring My jQuery Plugins: (function ($, window, document, undefined) { $.fn.loadPageContent = function (url, dataToSend) { url = url || window.location.href; dataToSend = dataToSend ? dataToSend : {}; return $.post(url, data ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

Display information on a web page based on user input using HTML

I've hidden other p tags and divs using display:none, How can I make them visible after inputting my name? I'd like to type in my name and reveal all the content within the previously hidden div <form method="post"> <p> < ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Guide to utilizing Materialize with Angular 2

For the past 2 days, I've been struggling with an issue. I'm fairly new to Angular 2 and I'm attempting to use Materialize with Angular 2. I managed to resolve a couple of errors that were asking me to update the TypeScript version, which I ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...