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

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

Is it possible to vertically center a child div within its parent container using JavaScript when the page loads without explicitly setting its position?

Using JavaScript to vertically center a child div within a fluid container involves calculating the height of both elements and positioning the child div accordingly. However, one issue faced is that the position is not set when the page loads. To solve ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

Sharing a session with a Django template using jQuery

I am attempting to use $.load() to load a Django template that contains {% if user.is_authenticated %}. However, when the template is rendered on the server in response to an AJAX-generated HTTP request, the user object is undefined. Here is my_template.h ...

One of the three identical paths in Node.JS is experiencing issues

I'm brand new to Node.js and currently working on creating a backend api for a project. I have 3 routes in my application: societies, users, and emails. //module for email functionality emailsModule = require('./api/routes/emails')(co ...

Enhancing Donut Chart with d3.js

After working for several hours, I'm having trouble getting my d3.js donut graph to update with new data. Here's my HTML: <body> <div id="pie"></div> <script src="pie.js"></script> </body> And he ...

What is the best method to extract the URL from an iframe div element using jQuery or JavaScript?

I have a dynamic way of getting my URL source, as shown in the code below. Is it possible to retrieve the URL from within the gettingiframe div, which is located inside an iframe? Below is the code snippet: <div id="gettingiframe"> <iframe sr ...

Updating an AngularJS directive following a service method invocation

My goal is to set up a reusable alert service that can be easily called from anywhere in my application with just: alertService.showAlert('warning', 'something went wrong!'); One example of where I want to use this is after an AJAX ca ...

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

Having issues with the sidebar malfunctioning and unsure of the cause

<html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> I've been working on creating a sidebar for my website, but it's not functioning as expect ...

Extracting all usernames of members present in a specific voice channel and converting them into a string using Node.js on Discord

Hey everyone, I'm looking for a code snippet that will help me retrieve all the members from a specific voice channel by using its ID. I also need to extract and store the usernames of these members who are currently in that particular voice channel w ...

Receiving an incorrect UTF-8 sequence in the JSON input

I currently have an ec2 server running with PHP version 5.3, hosting 2 virtual hosts: one for development and one for live production. Interestingly, on the development host, if someone uploads a file containing invalid UTF-8 characters, it simply ignores ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Error encountered while invoking web server method in C# through ajax resulting in a 500 Internal Server Error

Occasionally encountering a 500 internal server error when calling a server method from an AJAX request has left me perplexed. The inconsistency of the issue, sometimes working fine and sometimes not, is baffling. To add to the confusion, no changes were m ...

Steps to automatically navigate to a specific Div upon page initialization

Can someone help me understand why my code is scrolling to a div and then returning back to the top of the page? $("#Qtags").click(function(){ $('html, body').animate({'scrollTop' : $($(this).attr('href')).offset().top}, ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

Is there a way to make the hoverzoom effect only apply to a specific object instead of all objects?

I'm currently troubleshooting my code in order to implement a hover effect on Mui <cards> when a user hovers over the object. I have managed to make it work partially, but the issue is that the effect gets applied to all objects instead of just ...