What is the best way to halt the execution of content scripts in the active tab?

I am currently developing a Google Chrome Extension and have come across a bug that I am struggling to fix on my own.

The extension works as intended when switching to Youtube's Dark Mode on a single tab. However, if you are on Youtube and open a new tab by Ctrl/Cmd clicking a link, the content.js script is triggered again, causing the current tab to turn white while the new tab remains dark.

In the case where you are in a dark-themed tab, any child tabs should automatically inherit the dark theme.

manifest.json:

{
    "manifest_version": 2,

    "permissions": [
        "https://www.youtube.com/*",
        "activeTab"
    ],

    "background": {
        "scripts": ["background.js"],
        "persistant": false
    },

    "browser_action": {
        "default_title": "Enable Youtube Dark Mode."
    },

    "content_scripts": [
    {
      "matches": ["https://www.youtube.com/*"],
      "js": ["content.js"]
    }]
}

background.js:

//var alreadyTriggered = false;

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "clicker.js"});
});
/*
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    alreadyTriggered = false;
});*/

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
    //if (!alreadyTriggered) {
        chrome.tabs.executeScript(null, {file: "clicker.js"});
        //alreadyTriggered = true;
    //};
    return true;
});

content.js:

var currentTime = new Date();

if ((currentTime.getHours() <= 7) || (currentTime.getHours() >= 19))
{
    var darkMode = document.body.getAttribute("dark");
    if (!darkMode) {
        chrome.runtime.sendMessage(window.location.href, function(result) {});
    };
};

It seems like I might be using activeTab incorrectly. Any assistance would be greatly appreciated. Thank you!

clicker.js:

stepOne();

function stepOne() {
    try {
        var buttons = document.querySelectorAll("button.ytd-topbar-menu-button-renderer");
        buttons[0].click();
        stepTwo();
    }
    catch(error) {
        setTimeout(stepOne, 250);
    }
}

function stepTwo() {
    try {
        buttons = document.querySelectorAll("paper-item.ytd-account-settings");
        buttons[0].click();
        stepThree();
    }
    catch(error) {
        setTimeout(stepTwo, 100);
    }
}

function stepThree() {
    try {
        buttons = document.querySelectorAll("paper-toggle-button.style-scope.ytd-account-settings");
        buttons[0].click();

        document.body.click();
    }
    catch(error) {
        setTimeout(stepThree, 100);
    }
}

Answer №1

After trying numerous options, I found success by implementing the following strategies: incorporating window.onload = doStuff();

In addition, it was crucial to ensure that the value assigned to darkMode was specifically null, rather than undefined.

This advice may prove beneficial for individuals who have been tirelessly adjusting their code without seeing desired results.

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

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Effectively handle multiple connections from nodejs to postgres using the pg library

I need to run a script that performs multiple queries using the pg library for managing connections. However, I am facing an issue where my program stops working when the connection pool is full and does not queue future queries. I have tried setting the p ...

bringing in a js file with an import statement at the beginning

I am looking to import a file that brings in another file for use across multiple pages Here is my folder structure: js modules momentum-scrolling index.js about.js contact.js Contents of momentum-scrolling.js: import LocomotiveScroll from &a ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Find a way to incorporate social media features into a web application that functions intermittently

Currently, I am in the process of developing a social media app and working on integrating a search feature to enable users to find friends. The code I have below seems to be functional at times but not consistent (quite frustrating!) The issue seems to st ...

Webpack 4 Failing to Properly Render Select Tag

I am encountering an issue with a basic select element that is not displaying correctly due to Webpack. The screenshot below illustrates the final rendered page source, where the closing tag for the select element has been incorrectly positioned before the ...

Is it possible to replace a server-side templating engine with Angular 2's server-side pre-rendering?

As a novice in web development, I have recently been exploring angular 1.x, react.js, and angular 2 (eventually deciding on angular 2). Lately, I've been intrigued by the concept of server-side pre-rendering. In my understanding, this process is ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

Displaying concealed fields using the Bootstrap table detail formatter

I am attempting to create a customized detail formatter for my table, but I am encountering several fields with underscores, such as: _id: undefined _class: undefined _data: [object Object] This occurs when I click the plus button. <head> &l ...

Ember's distinctive feature: Named Block Helpers

Can we create "named blocks" in a different way? For instance, {{#customBlock "repeatableBlock"}} {{!-- block containing numerous properties and data that may become messy if hardcoded multiple times --}} {{/customBlock}} Then, elsewhere in the code, {{ ...

Bringing in a legacy ES5 module for integration within a ReactJS component

Attempting to incorporate an ES5 module into a new ReactJS application has been quite the challenge. I'm struggling with understanding the correct way to import the module so that the main function within it can be accessed and executed. Currently, m ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...