2014-01-08 29 views
0

我知道我们不能这样做,但我想知道是否有另一种方法做以下的事情对外网站:使用JavaScript在iframe或DIV

<iframe width="100%" frameborder="0" height="100%" src="http://google.com"></iframe> 

<script> 
$(function(){ 
    $(document.body).bind('mouseup', function(e){ 
     var selection; 

     if (window.getSelection) { 
      selection = window.getSelection(); 
     } else if (document.selection) { 
      selection = document.selection.createRange(); 
     } 

     selection.toString() !== '' && alert('"' + selection.toString() + '" was selected at ' + e.pageX + '/' + e.pageY); 
    }); 
}); 
</script> 

所以我想要做的在iframe中的操作。例如,打开一个包含选定文本的弹出窗口。

回答

0

不,这是不可能的,如果iframe src与父容器域的域不同于您的代码。

但如果两个域是相同的,那么你可以访问iframe的dom。

为此,你需要iframe的第一次访问innerDoc由:

var iframe = document.getElementById('html2'); 
var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 

一旦你的对象,现在你可以访问:

innerDoc.getElementById('divId');