Home > Article > Web Front-end > How Can I Access the Parent URL from an Iframe Across Subdomains?
Accessing Parent URL from iframe Across Subdomains
Accessing the URL of the parent page from within an iframe is generally straightforward if both pages reside on the same domain. However, when the iframe and the parent page are on different subdomains, cross-domain scripting restrictions prevent direct access to the parent's URL.
Cross-Site Scripting Restrictions
Cross-site scripting vulnerabilities occur when a malicious script on one website is able to access and execute code on another website. Browser security policies enforce strict restrictions to prevent such vulnerabilities from exploiting sensitive data. One of these restrictions is that scripts cannot access data from websites on different domains without explicit permission.
Subdomains and Cross-Site Scripting
While subdomains logically appear related to their primary domain, from a security standpoint, they are treated as separate entities. Therefore, when an iframe on one subdomain attempts to access the URL of the parent page on another subdomain, the browser interprets this as a cross-site scripting attempt and denies access.
Alternative Solution
If the requirement is solely to obtain the URL of the main page (the browser's address bar URL), a workaround is available:
var url = (window.location != window.parent.location) ? document.referrer : document.location.href;
This code checks if the iframe and the parent page are on different subdomains. If they are, it uses the document.referrer property to obtain the URL of the page that linked to the iframe. If they are not on different subdomains, it uses the document.location.href property to retrieve the URL of the parent page.
Note:
The above is the detailed content of How Can I Access the Parent URL from an Iframe Across Subdomains?. For more information, please follow other related articles on the PHP Chinese website!