My Chrome Extension is only working when I refresh the website I have it matched to. If I navigate the website, it will not successfully load, however, I do see the content-script being re-run in the console. It seems to fail because it's not finding the HTML elements I'm looking for. On refresh, it can find those HTML elements, and works fine.
I've been trying a few things like chrome.tabs.onUpdated.addListener and MutationObserver but couldn't figure it out. Most likely because my JS skills are fairly limited.
Link to the extension documents:
https://www.dropbox.com/s/x31uvkdpdcnhchz/chrome-ext-stack-example.zip?dl=0
How can I get the content-script to find the HTML elements as I navigate without always having to refresh?
Any thoughts on what I'm screwing up?
Thank you!
manifest.json
{
"manifest_version": 3,
"name": "Test",
"description": "Example for StackOverflow",
"version": "0.0.1",
"host_permissions": ["<all_urls>"],
"permissions": ["storage", "activeTab", "scripting", "tabs", "webNavigation"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://www.zillow.com/homedetails/*"],
"js": ["ballpark.js"],
"css": ["main.css"]
}
],
"web_accessible_resources": [
{
"resources": ["/images/*"],
"matches": ["<all_urls>"]
}
]
}
background.js
function injectScript(tabId) {
chrome.scripting.executeScript(
{
target: {tabId: tabId},
files: ['ballpark.js'],
}
);
}
// adds a listener to tab change
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// check for a URL in the changeInfo parameter (url is only added when it is changed)
if (changeInfo.url) {
// calls the inject function
injectScript(tabId);
}
});
ballpark.js
var offerPrice;
// setTimeout(startWidget, 2000);
startWidget()
function startWidget() {
if(location.href.match(/homedetails/g)) {
console.log("YES Zillow Home Details URL");
getAskingPrice();
insertWidget();
} else {
console.log("NO Zillow Home Details URL");
}
}
// Get Price from Zillow
function getAskingPrice() {
var askingPrice = document.querySelector('[data-testid="price"] span');
if(askingPrice !== null) {
offerPrice = parseFloat(askingPrice.innerText.replace(/\$|,/g, ''));
console.log(offerPrice + " Offer Price");
} else {
console.log("Null Asking Price");
}
}
// Find Zillow widget to insert the extension widget
function insertWidget() {
const select_div_for_bpd = document.querySelector('div.Spacer-c11n-8-65-2__sc-17suqs2-0');
if(select_div_for_bpd !== null) {
const ballpark_container = document.createElement("div");
ballpark_container.setAttribute("id", "ballpark-container");
select_div_for_bpd.appendChild(ballpark_container);
ballpark_container.innerHTML = `
<div class="ballpark-roi-container">
<div><h1>${offerPrice}</h1> Offer Price</div>
</div>
`;
} else {
console.log("Cannot insert ballpark widget");
}
}