0

I'm trying to select a div used in an iframe, but the select instruction always return an empty object, any idea how to solve this please:

console.log($(this).contents().find('div'));

JSFiddle: https://jsfiddle.net/8jxvry4c/6/

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
Dro
  • 21
  • 3
  • 1
    Possible duplicate of [Cannot select an element inside an iframe](https://stackoverflow.com/questions/32652813/cannot-select-an-element-inside-an-iframe) – Bucket Jun 22 '18 at 13:32

2 Answers2

0

Div is not accessible because it is not part of your DOM but part of iframe which itself consist different DOM for some other place.

In order to get div of iframe, you need to fetch all content of iframe and then find the div you wanted.

Following code can be used to fetch iframe content but it should be within same domain if not it will throws cross domain error

$('iframe').contentWindow.document.body.innerHTML

Or you can use cross-document messaging in Javascript where message is sent to iFrame and iFrame respond accordingly.

Main page

 myIframe.contentWindow.postMessage('hello', '*');

iframe

window.onmessage = function(e){
    if (e.data == 'hello') {
        alert('It works!');
    }
};

You can refer this link for more detail.

There are also some plugin available to perform these kinds of task more swiftly.

Sandeep Garg
  • 1,292
  • 1
  • 13
  • 31
  • How can I fetch the content of iframe? – Dro Jun 22 '18 at 13:38
  • Thanks, so if its not in the same domain there is no way to manipulate a div under iframe? – Dro Jun 22 '18 at 13:40
  • There are some ways which can be used to manipulate iframe content but that require managing messaging sending and receiving across iframe and your html – Sandeep Garg Jun 22 '18 at 13:44
0

You can't access to DOM of a different domain because of Same-origin policy

Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.

This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

But you can accomplish this on server side of course performming a GET/POST request. And again you can't perform a GET/POST request from javascript (ajax) unless the other domain have Access-Control-Allow-Origin header.

Emeeus
  • 5,072
  • 2
  • 25
  • 37