Access an element inside a dynamically-created, cross-domain iFrame? [duplicate]

六眼飞鱼酱① 提交于 2020-01-03 04:46:12

问题


I want to access an element inside an iFrame, but because of the way the iFrame is being called, I am not succeeding.

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

The iframe is on a different subdomain:

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

Setting a timeout or an event listener for when the iframe is loaded, did not help.


回答1:


Both documents are placed on different (sub)domains, by default they are not able to interact via javascript.

You must set the domain of both documents to the same value.

Put this somewhere in the <head/> of both pages:

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

...then wait for the onload-event of the iframe and you should be able to access the document inside the iframe from the parent page(and vice versa).

Sample-Script for GreaseMonkey(simply overwrites the body of the 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){}
}


来源:https://stackoverflow.com/questions/28309576/access-an-element-inside-a-dynamically-created-cross-domain-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!