How to call functions in the original page(tab) in

2019-01-13 10:53发布

问题:

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?

回答1:

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
});


回答2:

You can also simply write in your content script:

location.href="javascript:greeting(); void 0";