Reputation: 365
I would like to create an extension to inject html into every page opened as soon as it is installed without reloading.
webpage.html:
<html>
<head>
<meta charset="utf-8" />
<title>Extension</title>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
};
</script>
</head>
<body>
<a href="javascript:go();">Click me</a>
</body>
</html>
manifest.json:
{
"name": "Chrome Extension Test",
"version": "0.1",
"description": "Test",
"manifest_version": 2,
"background" : {
"persistent": true,
"scripts": ["background.js"]
},
"permissions": ["http://*/*", "https://*/*"],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"]
}]
}
content_script.js:
(function() {
document.addEventListener("hello", function(data) {
chrome.runtime.sendMessage("test");
});
})();
background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
alert("message received");
console.log("background message received");
});
If the extension is already installed, it works. But if the extension is installed after loading web page, the content script can't receive an event dispatched from the web page unless reload.
Is there a way to receive the event in content script without reloading?
Upvotes: 0
Views: 2515
Reputation: 77482
There is a long canonical answer here.
In short, if you need your content script on initialization, you should do a chrome.tabs.query({}, ...);
at the background script initialization, that would inject scripts in all tabs with chrome.tabs.executeScript({file: "content_script.js"});
.
Upvotes: 3