Is there a better way to Check if the active chrome tab is a Google search result page (SERP) javascript

Issue

This Content is from Stack Overflow. Question asked by Arthur Clinkscales

Is there a better way to Check if the active chrome tab is a Google search result page (SERP) javascript
Apologies in advance if this is not a proper question.

currently using

// Checking if the active tab is a Google search result page (SERP)
chrome.tabs.query({ active: true }).then((tab) => {
  currentTabId = tab[0].id;
  let url = new URL(tab[0].url);
  let hostname = url.hostname;
  let q = url.searchParams.get("q");
  if (q != null && hostname.indexOf("google.com") != -1) {
    chrome.scripting.executeScript({
      target: { tabId: tab[0].id },
      files: ["content_search.js"],
    });
  } else {
    document.getElementById("invalid-message").style.display = "block";
  }
});

It intermittently triggers the invalid-message even if it’s a SERP page. Then the only way to get it to work is by killing the chrome process and restarting.

Is there a better way like an API for this?
Thanks in advance.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?