I want to inject content script dynamically from my background script.
The following is the background script
background.js
chrome.runtime.onInstalled.addListener((event) => {
chrome.scripting
.registerContentScripts([
{
id: "SCROLL_LISTENER_CONTENT_SCRIPT",
js: ["content.js"],
matches: urls,
runAt:"document_idle"
},
])
.then(() => {
console.log("content script registered");
})
.catch((error) =>
console.log("Error while registering content scripts", error)
);
}
});
});
content.js
function handleScroll() {
console.log("User scrolled")
const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = (winScroll / height) * 100;
console.log(scrolled)
chrome.runtime.sendMessage({text: "user scrolled"});
}
window.addEventListener("scroll",handleScroll);
In the background script the message "content script registered" is being logged. But when I open a matching url as specified I found no log for "User scrolled".
PS: Although when I am registering this script statically, i.e.. from manifest.json. It works