I have extension which prepends certain query parameters to a URL after toggling an input box. But, it drops off when navigating to another page on the same domain.
My goal – I want to persist the query parameter ?active=true
across the same domain. For example:
www.example.com?active=true
www.example.com/product/main?active=true
www.example.com/help?active=true
Heres what I have so far:
popup.html
– Heres the Input I interact with to run JS script that adds the query parameter:
<input type="checkbox" name="query" id="queryParams">
popup.js
– Heres the script that prepends query parameter
const queryParamaOptions = document.querySelector('#queryParams');
function toggleQueryParams(e) {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => {
if (e.target.checked === false) {
chrome.storage.local.set({
query: false
});
return;
} else {
chrome.storage.local.set({
query: true
});
// Heres where parameter is created
const params = encodeURI('active=true');
const url = tabs[0].url;
const hashStart = url.indexOf('#') === -1 ? url.length : url.indexOf('#');
const querySymbol = url.indexOf('?') === -1 ? '?' : '&';
var newUrl = `${url.substring(
0,
hashStart
)}${querySymbol}${params}${url.substring(hashStart)}`;
// Refresh page with new URL
chrome.tabs.update(tabs[0].id, { url: newUrl });
}
});
}
queryParamaOptions.addEventListener('click', (e) => toggleQueryParams(e));
Current thoughts
- I am thinking to store the domain in localstorage when I first run
toggleQueryParams
- Use something like
chrome.tabs.onUpdated
to watch for url changes onchangeInfo.url
within the background script because the pop.up is closed at this point whilst navigating different pages - Use an if condition to check if the stored domain matches the current domain. If so then run
toggleQueryParams
Any thoughts?