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

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

问题描述

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



例如:

原始页面(标签)

 < HTML> 
< head>
< title>原始网页< /标题>
< script>
函数greeting(){
alert(Ohayou!);
//此处的其他代码
}
< / script>
< / head>
< body>< / body>
< / html>

然后我想从Google Extensions的原始页面调用函数greeting。
我该如何做到以上几点?

解决方案

对于第一部分,您可以使用这个很好的答案:将代码插入页面上下文使用内容脚本



在内容脚本中调用一个函数很容易。您可以创建您自己的活动,然后您可以收听在您的内容脚本中。
这可以这样工作:

注入的代码

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

//触发事件
document.dispatchEvent(evt);

内容

  document.addEventListener('myCustomEvent',function(){
//做任何必要的事情
});


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

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

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