-->

bind event to iframe's content and trigger it

2020-07-23 05:40发布

问题:

I have isolated very strange bug from our current project:

index.html (demo) and iframe.html

do:

1) click at the first input and select any date

you will see - "datepicker changed inside iframe!"

2) click at the second input, write some symbols and press at any free space at the page

you will see - "usual_input changed inside iframe!" + "usual_input changed outside iframe!"

inside iframe:

<input id="datepicker" /> <input id="usual_input" />

binded at index.html to the change event at this inputs:

$(this).contents().find("#datepicker").change(... (1)
$(this).contents().find("#usual_input").change(... (2)

binded at iframe.html to the change event at this inputs:

$("#datepicker").change(... (3)
$("#usual_input").change(... (4)

But №1 dont work in any browser!

jquery ui's datepicker trigger change event 100% correctly. why we cant bind to it outside an iframe?

回答1:

You can access the window element of the iframe by:

$(this)[0].contentWindow.$("#datepicker")

Or this might work too:

this.contentWindow.$("#datepicker");

I hope that helped.



回答2:

very intesting conclusion:

there are 2 jquery objects: main_$ and iframe_$

main_$ can control iframe_$

iframe_$ cannot control main_$

iframe_$ cannot trigger events to main_$

main_$(iframe).contents().find("element").bind("event"); will not work

only standart (input, select and textarea)'s events sended by browser can be catched anywhere

best solution finded by JCOC611 is to replace temporarily main_$ by iframe_$

var main_$ = $;
$ = $(iframe).get(0).contentWindow.$;
//many logick which works perfectly without iframes
$ = current_$;

you can of course use main_$ and iframe_$ independently

PS

dont remember very old jquery bug in the worst browser in the world - ie

$("...").find("iframe").ready(
    function() {
        //this == iframe.contentDocument
        this.contentWindow == undefined;
    }
);

get iframe's window only by specific path

$("...").find("iframe").get(0).contentWindow

and it work cross-browser! :3