Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to detect a click event on a cross domain iframe
var myConfObj = {
iframeMouseOver : false
}
window.addEventListener('blur',function(){
if(myConfObj.iframeMouseOver){
console.log('Wow! Iframe Click!');
}
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseover',function(){
myConfObj.iframeMouseOver = true;
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseout',function(){
myConfObj.iframeMouseOver = false;
});
@miguelmota

This comment has been minimized.

Copy link

@miguelmota miguelmota commented Feb 18, 2014

Very useful! Too bad it doesn't work on mobile devices

@yan-shcherbakov

This comment has been minimized.

Copy link

@yan-shcherbakov yan-shcherbakov commented Mar 25, 2014

Hey thanks a lot for this one! This is quite slick!

@tbuchok

This comment has been minimized.

Copy link

@tbuchok tbuchok commented Feb 5, 2015

thanks this was very helpful.

@JeremyFan

This comment has been minimized.

Copy link

@JeremyFan JeremyFan commented Jun 29, 2015

Useful! Thanks!
But sometimes window does not focus and can not trigger the blur event, so I focus it when mouseover: window.focus();

@adiwithadidas

This comment has been minimized.

Copy link

@adiwithadidas adiwithadidas commented Jul 31, 2015

Yes, Very useful, but I think it only detects once, when focus changes from main window to iframe window ....

@KenyWan

This comment has been minimized.

Copy link

@KenyWan KenyWan commented Aug 14, 2015

Thank you so much! It's very helpful! 👍

@lukehatfield

This comment has been minimized.

Copy link

@lukehatfield lukehatfield commented Sep 29, 2015

Saved me :)

@AlexandraKlein

This comment has been minimized.

Copy link

@AlexandraKlein AlexandraKlein commented Nov 6, 2015

Pretty cool. Do you have a solution if the iFrame is at the top of the page at full width? In this case, the user lands on the page with the mouse already ontop of the iframe, and must mouse out and back in for this to fire.

@koalabeer

This comment has been minimized.

Copy link

@koalabeer koalabeer commented Nov 13, 2015

awesome, thanks!

@namgiangle90

This comment has been minimized.

Copy link

@namgiangle90 namgiangle90 commented Mar 13, 2016

awesome. i'm looking for this. thanks !!!

@willianjusten

This comment has been minimized.

Copy link

@willianjusten willianjusten commented Apr 22, 2016

Awesoooome!! <3

@saigiridhar21

This comment has been minimized.

Copy link

@saigiridhar21 saigiridhar21 commented Jun 29, 2016

Saved me :)

@and-and

This comment has been minimized.

Copy link

@and-and and-and commented Jul 27, 2016

Awesome!!!!!

@DipoAreoye

This comment has been minimized.

Copy link

@DipoAreoye DipoAreoye commented Aug 23, 2016

Very helpful , thanks

@alucidwolf

This comment has been minimized.

Copy link

@alucidwolf alucidwolf commented Sep 20, 2016

Very useful. I am looking for a way to access a button inside the iFrame and trigger a click event when that button is clicked inside the iFrame that is on another domain.

This works great to trigger an event if the iFrame wrapper is clicked, but trying to go deeper into an element within the iFrame has proven difficult. Has anyone had success taking it this far?

Cheers!

@ankushchauhan9

This comment has been minimized.

Copy link

@ankushchauhan9 ankushchauhan9 commented Jul 26, 2017

thanx!!

@Toniiiio

This comment has been minimized.

Copy link

@Toniiiio Toniiiio commented Sep 4, 2017

@AlexandraKlein:
Just initialize iframeMouseOver as true?

@micdenny

This comment has been minimized.

Copy link

@micdenny micdenny commented Jan 23, 2018

I did a simple angular wrapper based on these suggestions: https://gist.github.com/micdenny/db03a814eaf4cd8abf95f77885d9316f so you can do this:

<div>
  <iframe appIframeTracker (iframeClick)="onIframeClick()" src="http://www.google.com"></iframe>
</div>
@maxyharr

This comment has been minimized.

Copy link

@maxyharr maxyharr commented Jan 25, 2018

Thanks for the solutions, but are there any that provide mobile support?

@chaitanya1248

This comment has been minimized.

Copy link

@chaitanya1248 chaitanya1248 commented Jan 29, 2018

@maxyharr - Use touch events in case of mobile. touchstart, touchend.

https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

@manjeetglv

This comment has been minimized.

Copy link

@manjeetglv manjeetglv commented Mar 27, 2018

@alucidwolf did you find any solution?

@Pretorians

This comment has been minimized.

Copy link

@Pretorians Pretorians commented Apr 2, 2018

Hi,
Solve the problem in this way for mobile and desktop.

$(document).ready(function()
 {
	window.addEventListener('blur',function(){		
	    if (document.activeElement instanceof HTMLIFrameElement) {
                //Click in Iframe.
	    	tagueoFocusForm("campo captcha no robot");
	    }
	});	
});
@gsumit1

This comment has been minimized.

Copy link

@gsumit1 gsumit1 commented May 30, 2018

window.addEventListener('blur',function(){
if (document.activeElement instanceof HTMLIFrameElement)
some code}

This content.js code is not working for firefox though it is working for chrome. The web page is consisted of multiple iframes. Any suggestion.

@dawaltconley

This comment has been minimized.

Copy link

@dawaltconley dawaltconley commented Jun 4, 2018

For me, adding a 0 second timeout to @Pretorians suggestion made it work in Firefox. The problem seems to be that, at the time Firefox fires the blur event, it has not yet updated the document.activeElement, so it evaluates to false.

	window.addEventListener('blur',function(){	
            window.setTimeout(function () {	
	        if (document.activeElement instanceof HTMLIFrameElement) {
	    	    console.log("iframe click");
	        }
             }, 0);
	});
@MichVollmer

This comment has been minimized.

Copy link

@MichVollmer MichVollmer commented Jun 6, 2018

As alucidwolf, I am looking for a way to access a button inside the iFrame and trigger a click event when that button is clicked inside the iFrame that is on another domain.

Has anyone had success taking it this far?

Michael

@bees4ever

This comment has been minimized.

Copy link

@bees4ever bees4ever commented Jun 29, 2018

Wow nice trick 👍

@sleshJdev

This comment has been minimized.

Copy link

@sleshJdev sleshJdev commented Oct 2, 2018

This solution is not working for FF v62, because when you click on iframe and redirecting to a new window/tab, blur event in not thrown. Unfortunately I didn't fund any workaround yet.

@sleshJdev

This comment has been minimized.

Copy link

@sleshJdev sleshJdev commented Oct 4, 2018

Here is how I track iframe click for FF/Chrome:

function () {
    const state = {};

    (function (setup) {
        if (typeof window.addEventListener !== 'undefined') {
            window.addEventListener('load', setup, false);
        } else if (typeof document.addEventListener !== 'undefined') {
            document.addEventListener('load', setup, false);
        } else if (typeof window.attachEvent !== 'undefined') {
            window.attachEvent('onload', setup);
        } else {
            if (typeof window.onload === 'function') {
                const oldonload = onload;
                window.onload = function () {
                    oldonload();
                    setup();
                };
            } else {
                window.onload = setup;
            }
        }
    })(function () {
        state.isOverIFrame = false;
        state.firstBlur = false;
        state.hasFocusAcquired = false;

        findIFramesAndBindListeners();

        document.body.addEventListener('click', onClick);

        if (typeof window.attachEvent !== 'undefined') {
            top.attachEvent('onblur', function () {
                state.firstBlur = true;
                state.hasFocusAcquired = false;
                onIFrameClick()
            });
            top.attachEvent('onfocus', function () {
                state.hasFocusAcquired = true;
                console.log('attachEvent.focus');
            });
        } else if (typeof window.addEventListener !== 'undefined') {
            top.addEventListener('blur', function () {
                state.firstBlur = true;
                state.hasFocusAcquired = false;
                onIFrameClick();
            }, false);
            top.addEventListener('focus', function () {
                state.hasFocusAcquired = true;
                console.log('addEventListener.focus');
            });
        }

        setInterval(findIFramesAndBindListeners, 500);
    });

    function isFF() {
        return navigator.userAgent.search(/firefox/i) !== -1;
    }

    function isActiveElementChanged() {
        const prevActiveTag = document.activeElement.tagName.toUpperCase();
        document.activeElement.blur();
        const currActiveTag = document.activeElement.tagName.toUpperCase();
        return !prevActiveTag.includes('BODY') && currActiveTag.includes('BODY');
    }

    function onMouseOut() {
        if (!state.firstBlur && isFF() && isActiveElementChanged()) {
            console.log('firefox first click');
            onClick();
        } else {
            document.activeElement.blur();
            top.focus();
        }
        state.isOverIFrame = false;
        console.log(`onMouseOut`);
    }

    function onMouseOver() {
        state.isOverIFrame = true;
        console.log(`onMouseOver`);
    }

    function onIFrameClick() {
        console.log(`onIFrameClick`);
        if (state.isOverIFrame) {
            onClick();
        }
    }

    function onClick() {
        console.log(`onClick`);
    }

    function findIFramesAndBindListeners() {
        return Array.from(document.getElementsByTagName('iframe'))
            .forEach(function (element) {
                element.onmouseover = onMouseOver;
                element.onmouseout = onMouseOut;
            });
    }
}
@aiglevn

This comment has been minimized.

Copy link

@aiglevn aiglevn commented Oct 19, 2018

Very Useful! Thanks!

@gwhitelaw

This comment has been minimized.

Copy link

@gwhitelaw gwhitelaw commented Nov 28, 2018

Nice one @dawaltconley

@jtabone16

This comment has been minimized.

Copy link

@jtabone16 jtabone16 commented Nov 30, 2018

Perfect!

@ANN0Y1NGHACKER

This comment has been minimized.

Copy link

@ANN0Y1NGHACKER ANN0Y1NGHACKER commented Dec 4, 2018

What if I have 4 iframes. I cant figure out how to separate them, when I click on one of them the function executes for all of them. My function is it zooms in the iframe when clicked but when i click 1 all of them get zoomed

@doughballs

This comment has been minimized.

Copy link

@doughballs doughballs commented Feb 27, 2019

ANN0Y1NGHACKER, here's how I targeted a specific iframe for a google captcha:

var frames = Array.from(document.getElementsByTagName('iframe'));
var recaptchaWindow;

frames.forEach(function(x){
if (x.src.includes('google.com/recaptcha/api2/bframe') ){
recaptchaWindow = x.parentNode.parentNode;
};
});

@nahidhasankakon

This comment has been minimized.

Copy link

@nahidhasankakon nahidhasankakon commented Mar 1, 2019

How to disable right click on iframe content.I have tried long time but can't solve it yet. I need this solution badly.Do u have any idea?

@kivervinicius

This comment has been minimized.

Copy link

@kivervinicius kivervinicius commented Jul 15, 2019

JQuery version

        var iframeMouseOver = false;
	$("YOUR_CONTAINER_ID")
		.off("mouseover.iframe").on("mouseover.iframe", function() {
			iframeMouseOver = true;
		})
		.off("mouseout.iframe").on("mouseout.iframe", function() {
			iframeMouseOver = false;
		});

	$(window).off("blur.iframe").on("blur.iframe", function() {
		if(iframeMouseOver){
			$j("#os_top").click();
		}
	});
@yaquawa

This comment has been minimized.

Copy link

@yaquawa yaquawa commented Aug 9, 2019

Thanks! I created a script to simulate click event propagation of iframe.🥳

propagate_iframe_click_event.js

@ssoulless

This comment has been minimized.

Copy link

@ssoulless ssoulless commented Nov 4, 2019

Could somebody provide an example to add mobile support?

@ssoulless

This comment has been minimized.

Copy link

@ssoulless ssoulless commented Nov 9, 2019

I just created a bounty on StackOverflow for the one who tell me how to add mobile support to this code

@gusdewa

This comment has been minimized.

Copy link

@gusdewa gusdewa commented Jun 25, 2020

Thanks for this.

When we have cross-domain iframe, this will stop triggering the click on the iframe it self.
Any idea how to trigger both the parent blur event and the iframe click event?

@azu-kodix

This comment has been minimized.

Copy link

@azu-kodix azu-kodix commented Sep 9, 2020

If page has multiple iframes then event will only fire the first time, unless you return focus to the page. Hmm..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.