Arpana
Arpana

Reputation: 11

detect a change in url of iframe

I have an html page with iframe window in it. I want a variable to capture value as 0 when URL of iframe remains the same as initial and variable as 1 when there is a navigation within iframe.

Upvotes: 0

Views: 3842

Answers (1)

maxisme
maxisme

Reputation: 4245

Maybe something like this:

var clicked = 0;
$('iframe').load(function(){
        var iframe = $(this).contents();
        //notices if a tag is clicked within iframe
        iframe.find("a").click(function(){
               clicked = 1;
        });
});

Or you could mean something like this(?):

var clicked = 0;
$('iframe').load(function(){
        //store URL
        var src = $("a").attr('src');
        var iframe = $(this).contents();
        //notices if a tag is clicked within iframe
        iframe.find("a").click(function(){
               //has the URL changed?
               if(src != $(this).attr('src')){
                   clicked = 1;
               }else{
                   clicked = 0;
               }
        });
});

Final tested script with .link being the link inside the iframe:

var clicked = 0;
$(document).ready(function() {
    $('iframe').load(function(){
            var iframe = $(this).contents();
            var src = iframe.find(".link").attr('href');
            //notices if a tag is clicked within iframe
            iframe.find(".link").click(function(){
                   //has the URL changed?
                   if(src != iframe.find(".link").attr('href')){
                       clicked = 1;
                   }else{
                       clicked = 0;
                   }
                   console.log(clicked);
            });
    });
});

Upvotes: 1

Related Questions