javascript - 访问动态创建的跨域 iFrame 内的元素?

标签 javascript html iframe cross-domain greasemonkey

我想访问 iFrame 内的元素,但由于调用 iFrame 的方式,我没有成功。

This is the target page (www1.k9webprotection.com/...).

iframe 位于不同的子域上:

<iframe src="http://license.k9webprotection.com/..." ...></iframe>

在加载 iframe 时设置超时或事件监听器没有帮助。

最佳答案

两个文档都放置在不同的(子)域中,默认情况下它们无法通过 JavaScript 进行交互。

您必须设置domain两个文档的值相同。

将其放在<head/>中的某个位置两页的:

<script  type="text/javascript">
document.domain='k9webprotection.com'
</script>

...然后等待onload -iframe 的事件,您应该能够从父页面访问 iframe 内的文档(反之亦然)。

GreaseMonkey 的示例脚本(简单地覆盖 iframe 的主体):

// ==UserScript==
// @name        k9
// @namespace   k9
// @include     http://www1.k9webprotection.com/get-k9-web-protection-free
// @include     http://license.k9webprotection.com/license.jsp*
// @version     1
// @grant       none
// ==/UserScript==


document.domain= 'k9webprotection.com';
if(self===top){  
  try{
    $('iframe.getk9iframe').load(function(){
       $('body',this.contentDocument)
        .text('gotcha')
          .css({background:'red',fontSize:'3em'});
    });
    alert("I'm the document in the top-window");
  }
  catch(e){}
}

关于javascript - 访问动态创建的跨域 iFrame 内的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28309576/

相关文章:

javascript - 使用 javascript 过滤输入类型数字

javascript - 通过单击链接更改 iframe src

带圆 Angular 的 HTML/CSS 表格,javascript-border 更改不起作用

javascript - 如何从 iframe 调用主窗口中的 javascript?

javascript - 可靠地获取隐藏元素的高度

javascript - jquery UI 不会在新的 DOM 元素上执行

javascript - 如果 div 底部和屏幕匹配,则将 div 粘贴到屏幕

javascript - 如何在 HTML 和动态选择之间共享信息? - Angular JS

javascript - window.alert 关闭处理程序?

html - Flask - 通过嵌套 for 循环制作超链接的 HTML 表?