Retrieving jQuery instance within an iframe

2

I need to retrieve the instance of jQuery embedded in my iframe, as we know there are several ways to retrieve the jQuery instance, with references $ , jQuery , window["$"] , window["jQuery"] .

The problem is that when I try to use this same method with an iframe the result is not the same, it follows the code I'm trying.

$("#frame").get(0).contentWindow.window["$"]

or

var iframeWindow = $("#frame").get(0).contentWindow; 
console.log( iframeWindow["$"] );
  

Demonstration of my test

    
asked by anonymous 30.03.2015 / 21:53

2 answers

2

Not neglecting the potential problems caused by the same-source policy , a possible solution for what you are looking for:

Example in JSFiddle .

HTML

<iframe id="bubu" width="300" height="300"></iframe>

JS

// Conteúdo da iFrame com jQuery incluído e um alert() para vermos que chegou lá
var H = '<html><body><h1 id="hh">JavaScript</h1>';
    H += '<scr' + 'ipt src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scr' + 'ipt>';
    H += '<scr' + 'ipt>$(document).ready(function() {';
    H += 'alert("yay");';
    H += '});</scr' + 'ipt>';
    H += '</body></html>';

// apanhar a iFrame
var myIframe = document.getElementById("bubu");

// Escrever o conteúdo que preparamos
var myIframeContent =  myIframe.contentDocument ||  myIframe.contentWindow.document;
myIframeContent.open();
myIframeContent.write(H);
myIframeContent.close();

// Apanhar a janela (window) da iFrame
var myIframeWin = myIframe.contentWindow || myIframe.contentDocument;

// Alguns navegadores não devolvem a Window, tentamos ir busca-la
if (!myIframeWin.document) {
    myIframeWin = myIframeWin.parentNode();
}

// A instancia de jQuery
alert(myIframeWin["$"]);

Note: Tested only on Windows 8.1 running Google Chrome.

    
31.03.2015 / 01:19
1

I made a method to scan the structure of the object and try to find objects stored under the key $ and jQuery .

Attention: here it took about 30 seconds to finish, but it might take longer.

The search has a maximum depth of 4 levels.

jsfiddle

In this way, you can see that this works:

var iframeWindow = $("#frame").get(0); 
var frame$ = iframeWindow.contentWindow.$;

Note: You will not be able to find the variable if the IFrame is not the same source as the container because the browser will otherwise block it. Probably if you configure the server CORS to accept share resources, then yes it will be possible, but in this case you will have to have control over the server that provides IFrame content.

Creating an empty IFrame in hand, leaving% c and% blank will also block your access to IFrame variables. I tested with the example you provided at first and it did not work.

jsfiddle - proving it does not work

    
31.03.2015 / 00:57