Chrome扩展程序:IFrame并收听其中的点击 [英] Chrome Extension: IFrame and listening to clicks within it

查看:421
本文介绍了Chrome扩展程序:IFrame并收听其中的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入一个iframe(frame.html,它是我的扩展的一部分)到网站的主体中,然后能够接收其中的两个按钮的点击事件。



碰到相同原产地规则等问题。



我相信这是一个相对优雅的解决方法,但我没有祝你好运。

postmsg /rel =nofollow>消息事件,让注入的iframe窗口与内容脚本进行通信(注意 security )。



下面是一个简单的例子。扩展插件通过内容脚本将IFRAME元素注入到所有查看的页面中。该框架包含一个带有按钮的页面。该按钮有一个点击处理程序,它将消息发送到顶部窗口。内容脚本拥有一个来自iframe的消息监听器,它会打开显示消息数据的警报。



manifest.json:

  {
name:Test,
version:0.0.1,
content_scripts:[ {
matches:[http:// * / *,https:// * / *],
js:[content.js],
run_at:document_end
}]
}

内容。 js:

  var iframe = document.createElement(iframe); 
iframe.src = chrome.extension.getURL(iframe.html);
document.body.appendChild(iframe);
$ b $ addEventListener(message,function(event){
if(event.origin +/== chrome.extension.getURL())
alert( event.data);
},false);



iframe.html:

 <!DOCTYPE html> 
< html>
< head>
< title>测试< /标题>
< / head>
< body>
< button id =button>点击我!< / button>
< script>
document.getElementById(button)。addEventListener(click,function(){
top.postMessage(clicked!,*);
},false);
< / script>
< / body>
< / html>


I would like to insert an iframe (frame.html which is part of my extension) into the body of a website and then be able to receive click events for two buttons inside it.

Running into problems with same origin policy, etc.

I'm sure there is a relatively graceful workaround for this, but I'm not having much luck finding it.

解决方案

You can use message events to let the injected iframe window communicate with the content script (take care about security).

Here is a simple example. The extension injects an IFRAME element into all viewed pages via a content script. The frame contains a page with a button. The button has a click handler which sends a message to the top window. The content script has a listener to messages coming from the iframe which opens an alert displaying the message data.

manifest.json:

{
  "name": "Test",
  "version": "0.0.1",
  "content_scripts": [ {
    "matches": [ "http://*/*", "https://*/*" ],
    "js": [ "content.js" ],
    "run_at" : "document_end"
  } ]
}

content.js:

var iframe = document.createElement("iframe");    
iframe.src = chrome.extension.getURL("iframe.html");
document.body.appendChild(iframe);

addEventListener("message", function(event) {
  if (event.origin + "/" == chrome.extension.getURL(""))
    alert(event.data);
}, false);

iframe.html:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
</head>
<body>
  <button id="button">Click me!</button>
  <script>
    document.getElementById("button").addEventListener("click", function() {
      top.postMessage("clicked!", "*");
    }, false);
  </script>
</body>
</html>

这篇关于Chrome扩展程序:IFrame并收听其中的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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