Tips for comparing URLs of the current active tab

Looking to create an adblocker specifically for a certain website.

I have successfully implemented code that removes ads on the homepage, but it is still affecting other pages such as movie pages. This results in the deletion of the information section, including posters and other content. I want this piece of code to only target the Homepage at or . The website uses AJAX and loads only once.

Here is the code responsible for removing ads on the homepage:


chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.message === 'Homepage') {

    var timer = setInterval(deletor, 1);

    function deletor() {
        timer;
        var slider = document.querySelector("#slider-con");
        var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
        var bannerMiddle = document.querySelector("#MainContent > iframe");
        var bannerRandom = document.querySelector("#MainContent > div:nth-child(3)");

            if (slider) {
                slider.parentNode.removeChild(slider);
            }

            if (bannerTop) {
                bannerTop.parentNode.removeChild(bannerTop);
            }

            if (bannerMiddle) {
                bannerMiddle.parentNode.removeChild(bannerMiddle);
            }

            if (bannerRandom) {
                bannerRandom.parentNode.removeChild(bannerRandom);
            }
};
    } else {
        return false;
    }
})

This background script sends the message:


chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.url == "net.adjara.com" || "net.adjara.com/Home" || "net.adjara.com/Home/") {
      chrome.tabs.sendMessage( tabId, {
        message: "Homepage",
        url: changeInfo.url
      })
      console.log("successful!");
    } else if (changeInfo.url == "net.adjara.com/Movie/main*" || "net.adjara.come/Movie/*"){
        console.log("Movie page");
    } else {
        return false;
    }
});

After adding a console.log statement, it seems like the code runs on every page load and even on other sub-domains. I intend for this code to operate solely on the homepage, while creating a separate custom script for movie sub-domains.

It feels like I might be overlooking something crucial.

Answer №1

It seems like you're almost there. Just as wOxxOm pointed out, the syntax of your comparisons in the if statements may need a little tweaking. To properly format your multiple or conditions, consider the following:

if (changeInfo.url == "net.adjara.com" || 
    changeInfo.url == "net.adjara.com/Home" ||
    changeInfo.url == "net.adjara.com/Home/") {
    // your code block
  }

Think of each || as starting a new comparison. You need to explicitly state what two items are being compared for equality between each ||. With the example above, the if statement will check each condition individually and execute the code block if any one of them is true. (Bonus tip: With multiple or statements, if any of them are true, the whole expression evaluates to true. It's all about logic!)

If you want to get a bit more advanced, you can achieve this using regex. By passing the changeInfo.url string and checking if it matches with net.adjara.com at the beginning, you can simplify your code.

if (changeInfo.url.match(/^net.adjara.com/) {
   // your code block
}

The forward slashes surrounding the pattern indicate that it's a regex, the ^ signifies the start of the string, followed by the specific string to match against.

Keep in mind that this regex approach may need adjustment based on your actual URL structure. If your URLs begin with "http://" or "https://", you might want to explore other regex patterns or utilize the String.prototype.includes() method. You know your data best!

Best of luck with your coding!

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

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

What is the best way to keep my data within a global variable?

$(function(){ let spaceTravelersData; $.getJSON('http://api.open-notify.org/astros.json', retrieveData); function retrieveData(data) { spaceTravelersData = data; } alert(spaceTravelersData.people[0].name) }); I a ...

Retain values of JavaScript variables acquired by their IDs even after a page refresh

I have a JavaScript function that retrieves HTML input values and inserts them into a table. However, when I refresh the page, those values are reset to null. How can I prevent this and keep the values visible after a refresh? I believe setting and getting ...

Instructions on calling a function with AngularJS ng-click in a template rendered by a Grails controller

Is there a way to invoke a function using angularjs ng-click on a template that is rendered from a grails controller? I have tried, but the jQuery function call seems to work fine while the ng-click() function does not. What am I missing here? I'm rea ...

Maintain consistent width of a page across different mobile devices

Currently, the content on my page does not have any viewport settings. It is simply using a 25% left and right margin for the entire content area. The issue arises when accessing the page from a mobile device, as the width adjusts to match the screen size ...

Issues arise with req.body being undefined when using node.js in conjunction with Express version 4.16.X and Body-Parser version

Recently, I began using node.js to construct a RESTFul API. Currently, my focus lies in inserting data through POST requests with JSON in the body. However, I encountered an issue where the req.body always returned as undefined. Upon investigating further ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

Accessing the clandestine div via direct hyperlink

I have incorporated a toggle plugin from this website to display hidden divs. Each hidden div is identified by a unique id. Is there a method to show a specific div using a direct link? For instance, by entering domain.com/page.php#HiddenDiv2, it should ...

JavaScript function that takes an array of large objects and returns an array of smaller objects

Consider this scenario: I have a collection of large objects consisting of various attributes like ID, type, title, count, and more. { "id": "0165a74c-2545-40f7-9145-b95f5e5cb77e", "type": 4, "title": "My Title", "delete": false, "dele ...

Background that stretches to 100% width but only fills to the right side

UPDATE: I figured out why it wasn't working - the element with a width of 100% was nested inside a div with the class "container," removing that solved the issue! (I don't have enough reputation to answer my own question yet, just wanted to updat ...

Issue with strange behavior of CSS cursor with images

Is there something blatantly obvious that I'm missing here? My goal is to replace the cursor css property with a png, as shown in this example here I was able to get it working with the 'happy.png' demo, but for some reason it won't wo ...

Unspecified data returned from PHP script via jQuery AJAX

Encountering an issue while trying to use AJAX to get a PHP response from a form. The JavaScript appears to be correct as it functions when the content of login_ajax.php is reduced to just: echo 'CORRECT' //or echo 'INCORRECT' Howev ...

The div keeps appearing multiple times while the button remains inactive

In order to create a password confirmation form with validation, you need to have two input fields - one for entering a new password and another to confirm the password. The goal is to display a message saying "please enter the password above" below the ...

What are the steps to create parallel curves in three.js for road markings?

My goal is to create parallel curved lines that run alongside each other. However, when I try to adjust their positions in one axis, the outcome is not what I expected. The code I am using is fairly simple - it involves a bezier curve as the central path ...

unable to toggle collapse functionality of bootstrap 3 navbar

My navbar was recently modified, but now the toggle button is not responding when clicked. Here is the code I am using. Can someone help me find the mistake? CODE: <body> <div class="navbar-wrapper"> <div class="container"> ...

How to incorporate visionmedia debug into an Angular 2 application using System.js, and effective ways to record messages?

Currently I am working on a MEAN stack application with Angular 2 as the frontend. The express backend has successfully utilized debug. However, I am facing issues while trying to import debug cleanly into either app.components.ts or main.module.ts. Any su ...

Troubleshooting: Why is my switch-case statement in TypeScript not functioning as expected

Here is a simple switch case scenario: let ca: string = "2"; switch (ca) { case "2": console.log("2"); case "1": console.log("1"); default: console.log("default"); } I am puzzled by the output of this code, which is as follows: 2 1 defa ...

Bar graph width in Chart.js is displayed horizontally

Check out the bar chart image here: https://i.sstatic.net/RLeZp.png This particular graph was created using the code snippet provided below: var myChart = new Chart(ctx, { type: 'horizontalBar', data: { labels: labels, ...

Tutorial on inserting a picture into muidatatables

Important Note: The image stored in the database is called "profileImage." I am looking to create a dynamic image object similar to other objects. When I input this code: { label: "Image", name: "profileImage" }, it simply displays the image endpoint as ...

I am unable to access Angular $scope in the HTML Template, although I can view it in the console log

I have been following some online tutorials and using the angularjs-template to start learning Angular. However, I am facing an issue where the page (html template) is not updating with the controller. It seems like there is a problem in how I've set ...