user10756951
user10756951

Reputation:

How to make some code running only on some specific domains

I am building a Chrome extension and in my contentScript, I have this line of code:

a.setAttribute("style", "border: 1.5px dashed "+ color +"; padding: 5px; display: inline-block !important;");

In my popup.html I got those radio buttons:

  <div style="float: left; width: 60%;">
      <h3>Where should we find prerender?</h3>
      <input type="radio" id="radio_serp" name="radios" checked="checked" style="margin-left: 15px;"><span class="radio">Only SERP</span><br>
      <input type="radio" id="radio_ev" name="radios" style="margin-left: 15px; margin-top: 6px;"><span class="radio">Everywhere</span><br>
    </div>

I want to make it that if a user selects the first checkbox, the code will work only on Google SERP. If he selects the second checkbox, the line of code from contentScript will apply on every domain.

Is this possible and how? Thanks

Upvotes: 0

Views: 74

Answers (1)

Uncreative Name
Uncreative Name

Reputation: 321

First, store the currently selected option in the storage (you need the "storage" permission for that):

popup.js

let serpButton = document.getElementById("radio_serp");
serpButton.addEventListener("click", () => {
    if(serpButton.checked)
        chrome.storage.sync.set({
            mode: "serp_only"
        });
});

let otherButton = document.getElementById("radio_ev");
otherButton.addEventListener("click", () => {
    if(otherButton.checked)
        chrome.storage.sync.set({
            mode: "everywhere"
        });
});

You can check the current URL in the content script by using window.location and retrieve the mode by calling storage.get:

chrome.storage.sync.get("mode", result => {
    let mode = result.mode;
    if (mode === "everywhere")
        run();
    else if (mode === "serp_only" && (location.host.startWith("google.") || location.host.startWith("www.google.")) && location.pathname.startsWith("/search")) {
        run();
}
});

function run(){
    a.setAttribute("style", "border: 1.5px dashed "+ color +"; padding: 5px; display: inline-block !important;");
}

Upvotes: 1

Related Questions