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?