如何在 Chrome 扩展程序中调用原始页面(标签)中的函数 [英] How to call functions in the original page(tab) in Chrome Extensions

查看:39
本文介绍了如何在 Chrome 扩展程序中调用原始页面(标签)中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在制作 Chrome 扩展程序.我想从 Chrome 扩展中调用在原始页面(选项卡)中定义的 JS 函数.background.html 还是 Content_Script 调用它们并不重要.

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.

例如:

原始页面(标签)

<html>
<head>
<title>Original Page</title>
<script>
function greeting(){
    alert("Ohayou!");
    // some other codes here
}
</script>
</head>
<body></body>
</html>

然后我想从 Google Extensions 调用原始页面中的函数greeting".我该怎么做?

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:

注入代码:

var evt = document.createEvent('Event');
evt.initEvent('myCustomEvent', true, false);

// fire the event
document.dispatchEvent(evt);

内容脚本:

document.addEventListener('myCustomEvent', function() {
  // do whatever is necessary
});

这篇关于如何在 Chrome 扩展程序中调用原始页面(标签)中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆