Issue Explanation:
The problem you're encountering stems from the fact that your content script loses its execution context whenever the page reloads. When you simulate a search that triggers a page reload (for example, by dispatching a 'keydown' event with the 'Enter' key), the entire page—including your content script—is reloaded. This causes several issues:
- Variable Reset: Variables like
globalLoader are re-initialized, and any state stored in them is lost.
- DOM Elements Persistence: Elements you've added to the DOM (like your loader) persist across reloads unless explicitly removed, but your script loses the reference to these elements due to re-initialization.
- Interrupted Execution: The
await calls in your performMultipleSearches function don't survive the page reload, so the execution flow is disrupted.
As a result, the loader remains visible on the page because the script that was supposed to remove it no longer has a reference to the loader element after the page reloads.
Solution:
To fix this issue, you need to adjust your approach to handle page reloads or avoid them altogether. Here are the steps you can take:
-
Avoid Page Reloads: Modify your search simulation to prevent full page reloads. This can often be achieved by interacting with the page's JavaScript API or triggering search functions that update the page content dynamically (AJAX calls) without reloading.
-
Persist State Across Reloads: Use chrome.storage to store state information that can persist across page reloads, allowing your content script to regain context after a reload.
-
Detect and Remove Existing Loader Elements: Modify your script to check for existing loader elements upon startup and remove them if necessary.
-
Use a Background Script: Move the execution flow to a background script that isn't affected by page reloads. Communicate between the content script and background script using chrome.runtime.sendMessage and chrome.runtime.onMessage.
Updated Code:
Below is the modified version of your code incorporating these solutions:
// Content Script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "findSearchBox") {
const searchBox = findSearchBox();
if (searchBox) {
searchBox.focus();
searchBox.style.border = "2px solid red";
} else {
alert("No search box found on this page.");
}
} else if (request.action === "autoInputMultiple") {
performMultipleSearches(request.searchTerms);
}
});
function findSearchBox() {
const searchInputs = document.querySelectorAll('input[type="search"], input[name*="search"], input[id*="search"], input[class*="search"]');
if (searchInputs.length > 0) {
return searchInputs[0];
}
return null;
}
let globalLoader = null;
// At script startup, remove any existing loader
(function cleanupLoader() {
const existingLoader = document.getElementById('search-loader');
if (existingLoader) {
existingLoader.remove();
}
})();
function createLoader() {
// Check if loader already exists in the DOM
const existingLoaderElement = document.getElementById('search-loader');
if (existingLoaderElement) {
const messageElement = existingLoaderElement.querySelector('#loader-message');
globalLoader = {
updateMessage: (message) => {
console.log('Updating loader message:', message);
messageElement.textContent = message;
},
remove: () => {
console.log('Removing loader');
existingLoaderElement.remove();
globalLoader = null;
}
};
console.log('Loader already exists, returning existing loader');
return globalLoader;
}
console.log('Creating new loader');
const loader = document.createElement('div');
loader.id = 'search-loader';
loader.style.cssText = `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.5); display: flex;
justify-content: center; align-items: center; z-index: 9999;
`;
const messageElement = document.createElement('div');
messageElement.id = 'loader-message';
messageElement.style.cssText = `
color: white; font-size: 24px; text-align: center;
padding: 20px; background-color: rgba(0, 0, 0, 0.7);
border-radius: 10px;
`;
messageElement.textContent = 'Searching...';
loader.appendChild(messageElement);
document.body.appendChild(loader);
globalLoader = {
updateMessage: (message) => {
console.log('Updating loader message:', message);
messageElement.textContent = message;
},
remove: () => {
console.log('Removing loader');
loader.remove();
globalLoader = null;
}
};
return globalLoader;
}
async function performMultipleSearches(searchTerms) {
const searchBox = findSearchBox();
if (!searchBox) {
alert("No search box found on this page.");
return;
}
console.log('Creating loader for multiple searches');
const loader = createLoader();
let aggregatedResults = '';
try {
for (let i = 0; i < searchTerms.length; i++) {
const term = searchTerms[i];
console.log(`Searching for: ${term} (${i + 1}/${searchTerms.length})`);
loader.updateMessage(`Searching: ${term} (${i + 1}/${searchTerms.length})`);
searchBox.value = term;
searchBox.dispatchEvent(new Event('input', { bubbles: true }));
// Instead of triggering a 'Enter' key event, submit the form programmatically if possible
const form = searchBox.form;
if (form) {
form.dispatchEvent(new Event('submit', { bubbles: true }));
} else {
// Fallback to clicking a search button if present
const searchButton = document.querySelector('button[type="submit"], input[type="submit"]');
if (searchButton) {
searchButton.click();
} else {
alert("No way to submit the search found.");
return;
}
}
// Wait for the page content to update (not reload)
await waitForContentUpdate();
const pageContent = document.body.innerHTML;
aggregatedResults += `<div class="search-result"><h2>Results for "${term}"</h2>${pageContent}</div>`;
if (i < searchTerms.length - 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
console.log('All searches completed');
loader.updateMessage('Preparing results...');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Removing loader after searches');
loader.remove();
console.log('Displaying results');
displayResults(aggregatedResults);
} catch (error) {
console.error('Error during search:', error);
alert(`An error occurred during the search: ${error.message}`);
} finally {
console.log('Final check: Ensuring loader is removed');
forceRemoveLoader();
}
}
function displayResults(results) {
try {
console.log('Creating results container');
const resultsContainer = document.createElement('div');
resultsContainer.style.cssText = `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background-color: white; overflow-y: auto; z-index: 10000;
`;
resultsContainer.innerHTML = `
<div style="padding: 20px;">
<h1>Search Results</h1>
<button id="closeResults" style="position: fixed; top: 10px; right: 10px;">Close</button>
${results}
</div>
`;
console.log('Appending results container to body');
document.body.appendChild(resultsContainer);
console.log('Adding event listener to close button');
document.getElementById('closeResults').addEventListener('click', () => {
console.log('Closing results');
resultsContainer.remove();
});
} catch (error) {
console.error('Error displaying results:', error);
alert(`An error occurred while displaying results: ${error.message}`);
}
}
function forceRemoveLoader() {
const loader = document.getElementById('search-loader');
if (loader) {
console.log('Forcibly removing loader');
loader.remove();
}
globalLoader = null;
}
function waitForContentUpdate(timeout = 10000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const initialContent = document.body.innerHTML;
const checkContentChanged = () => {
if (document.body.innerHTML !== initialContent) {
resolve();
} else if (Date.now() - startTime > timeout) {
reject(new Error('Content update timeout'));
} else {
setTimeout(checkContentChanged, 100);
}
};
checkContentChanged();
});
}
Key Changes and Explanations:
-
Avoid Page Reloads: Instead of simulating the 'Enter' key, which often triggers a full page reload, the code now attempts to submit the search form programmatically or clicks the search button if available.
-
Content Update Detection: Replaced waitForPageLoad with waitForContentUpdate, which waits for the page content to change instead of waiting for a page reload.
-
Loader Management:
- At the top of the script, added a self-invoking function to remove any existing loader when the script starts.
- Modified
createLoader to check for an existing loader element in the DOM and reuse it if present.
- Ensured that the
loader object always references the actual DOM element, even after potential changes.
-
State Persistence: By managing the loader through DOM elements and checking their existence, we ensure the script can regain control of the loader after any page updates that don't involve a full reload.
Additional Recommendations:
-
Handle Single Page Applications (SPAs): If you're working with an SPA, ensure that the search actions and page updates are compatible with your approach.
-
Use Background Scripts: For more complex scenarios where you need to maintain state across page reloads, consider moving the main execution flow to a background script and using message passing to communicate with the content script.
-
Error Handling: Implement robust error handling to account for cases where forms or buttons aren't found.
Testing:
- Test your extension thoroughly on the target website to ensure that the modified approach works as expected.
- Check for any console errors that might indicate issues with selectors or event dispatching.
Conclusion:
By adjusting your script to avoid full page reloads and managing the loader's state through DOM checks, you should be able to resolve the issue of the loader persisting after searches are completed. This approach also makes your script more robust and better suited for modern web applications.