在 iframe 或 div 中将 JavaScript 与外部网站一起使用



我知道我们不能这样做,但我想知道是否有另一种方法可以做以下事情:

<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 中做一个动作。例如,打开包含所选文本的弹出窗口。

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

但是,如果两个域相同,则可以访问iframe的DOM

为此,您需要首先通过以下方式访问iframe的innerDoc:

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

获取对象后,现在您可以访问:

innerDoc.getElementById('divId');

最新更新