user1360768
user1360768

Reputation:

Getting error when URL of external Site in Iframe in Javascript or Jquery

alert(document.getElementById('external-site').contentWindow.location.href);

Hello all, this code is working in Chrome and showing "undefined" but in Mozila Firefox it is showing error.

Error: Permission denied to access property 'href'

Upvotes: 2

Views: 1525

Answers (3)

user3243420
user3243420

Reputation: 1

I was also getting the same error.

To overcome this error I used the following line of code:

alert(document.getElementById('external-site').contentWindow.document.location.href);

Upvotes: 0

Jochem
Jochem

Reputation: 2994

Since all you want to do is 'check' if it is external, why not catch the error? Seems to work in FF and Chrome. See jsFiddle.

try {
    alert(document.getElementById('external-site').contentWindow.location.href);
}
catch (err) {
    alert("undefined");
}

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

if document.getElementById('external-site') is referring to an iframe which is loading a page from a different domain then firefox runs into a same-origin policy error and you cannot access to window.location object

From MDN:

The same origin policy prevents a document or script loaded from one origin from getting or setting properties of a document from another origin. This policy dates all the way back to Netscape Navigator 2.0.

Upvotes: 2

Related Questions