1

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.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Fomo
  • 143
  • 9
  • Is it on the same domain, or do you control both domains? – AlienWebguy Feb 03 '15 at 22:02
  • 2
    I'm voting to close this question as off-topic because this looks like spam to promote the website being linked to – chiliNUT Feb 03 '15 at 22:03
  • For interactions between the main page and the iframed one, see [this kind of technique](http://stackoverflow.com/q/11769066/331508). – Brock Adams Feb 03 '15 at 23:27
  • @chiliNUT, linking to a target page is a very good thing for a Greasemonkey/Tampermonkey/userscript question. It is not spam and the OP's post could hardly be seen as boosting that site in any SEO-useful way. (Also note that Stack Exchange uses `rel="nofollow"` on all such links.) – Brock Adams Feb 03 '15 at 23:37
  • (some) code has since been added since that comment. The original post was only the first 2 lines. A post with very little description, zero code, and a link to an unrelated offsite page looks like spam. – chiliNUT Feb 03 '15 at 23:54
  • @chiliNUT, I edited the question after 100 seconds of analyzing the target page. Sure, it's a poor question. But, the offsite page is completely relevant in a userscript context like this one. – Brock Adams Feb 04 '15 at 00:13

1 Answers1

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){}
}
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201