I'm now making a Chrome Extension. I want to call JS functions that are defined in the original page (tab), from Chrome Extension. It doesn't matter whether background.html
or Content_Script
calls them.
For example:
Original page (tab)
<html>
<head>
<title>Original Page</title>
<script>
function greeting(){
alert("Ohayou!");
// some other codes here
}
</script>
</head>
<body></body>
</html>
Then I want to call the function "greeting" in the original page, from Google Extensions.
How can I do the above?
For the first part you can use this nice answer: Insert code into the page context using a content script.
To call a function back in your content script is easy. You can create your own event which you can then listen on in your content script.
This would work like this:
injected code:
var evt = document.createEvent('Event');
evt.initEvent('myCustomEvent', true, false);
// fire the event
document.dispatchEvent(evt);
contentscript:
document.addEventListener('myCustomEvent', function() {
// do whatever is necessary
});
You can also simply write in your content script:
location.href="javascript:greeting(); void 0";