Access an element inside a dynamically-created, cr

2019-06-11 07:24发布

This question already has an answer here:

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条回答
Deceive 欺骗
2楼-- · 2019-06-11 08:16

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){}
}
查看更多
登录 后发表回答