Home > Blockchain >  window.location.href creating infinite loop within Content Script for Google Chrome Extension
window.location.href creating infinite loop within Content Script for Google Chrome Extension

Time:08-04

I'm learning how to create chrome extensions and I want to add search params to a google search every time the user enters a new query. I have this loop within my contentScripts.js file and it is creating a infinite loop, so I added a conditional as seen in the code which solves it for when the users searches. However it still loops whenever the user is doing anything else on google.

Code:

const addCurrentSearch = () => {
const newUrl = 'https://www.google.com/search?q=in 2021 ';
let currentURL = window.location.href;
let updatedSearch = currentURL.replace('https://www.google.com/search?q=', newUrl);

if(!currentURL.includes(newUrl)){
  window.location.href = updatedSearch;
}};

CodePudding user response:

That's because the code isn't checking for anything else. Not sure if this will fit your needs but its at least an improvement :)

const addCurrentSearch = () => {
  const googleSearchPageUrl = 'https://www.google.com/search'
  const newUrl = 'https://www.google.com/search?q=in 2021 ';
  let currentURL = window.location.href;
  let updatedSearch = currentURL.replace('https://www.google.com/search?q=', newUrl);

if(!currentURL.includes(newUrl) && currentURL.includes(googleSearchPageUrl)){
  window.location.href = updatedSearch;
}};

Now we are also checking if the user is on the google search page and the newUrl hasn't been applied

  • Related