How can I detect if an iFrame gets redirected to a

2019-08-06 13:11发布

问题:

I want to list an iframe with a classified ad in it. Sometimes the vendors redirect the page to their homepage when the item is no longer available. I want to be able to identify this so I can de-index the item assuming it has sold. What is the best method to accomplish this?

回答1:

You can use jQuery's load function that fires onload or reload.

http://api.jquery.com/load/

You will need to store the number of times the iframe has reloaded.

Something like,

var reloaded = 0;
$("#iframe_id").load(function(){
    reloaded++;
});


回答2:

You can not detect the location of the iframe when it is in a different domain unless they have the proper headers set for CORS.

The only way to do it without worrying about the other domain is to have your serverside code run a check on the page and see if it redirects.



回答3:

On the frame load, detect what the URL is:

var frameLoadCount = 0;
var firstURL;

$('iframe').load(function() {
    if (frameLoadCount === 0) {
        firstURL = $(this).attr('src');
    } else {
        if (firstURL !== $(this).attr('src')) {
            // The iframe has been redirected.
        }
    } 
});

Basically the above code runs everytime the iframe has loaded, checks if it's the first time, if it is, assign the URL to a variable. If it has loaded more than once, check if the original url matches the current url.

This has benefits from just checking if it's loaded more than once, because you can target specific sources etc.