'Programatic content script injection returning same string after url change
Goal: Re-inject content script after a URL change and grab new name from the DOM
Problem: The same variable name returns after URL change. The idea is a new URL signifies a new name in the DOM that I would like to populate within my popup.html.
background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['contentScript.js']
});
}
});
contentScript.js - Should run after URL change
let name;
setTimeout(() => {
const recordNameEl = document.querySelectorAll('.recordId');
const recordNameString = recordNameEl[1].textContent;
const nameArray = recordNameString.split(' ');
name = nameArray[0];
// Set name in localStorage. Should reset to new name after URL change
chrome.storage.local.set({ name });
// Logs same name after URL changes. Console is defo reloading after each change
console.log(name);
}, 10000);
Surely a new context is created after each script execution triggered by URL change? Not sure why I am getting the same string even after URL change which triggers a console reload
In case your wondering
- I'm using
setTimeout()because the page takes so long to load. If I didn't then I'd get a reference error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
