Accessing Parent URL from Iframe
When working with iframes, it's often necessary to access the URL of the parent page from within the iframe. However, this can be problematic if the iframe and the parent page are not on the same subdomain.
Cross-Site Scripting and Subdomains
Cross-site scripting (XSS) occurs when a malicious script is executed on a web page that is trusted by a user. Stricter security measures have been implemented to prevent XSS, and these measures extend to iframes.
If the iframe and the parent page are not on the same subdomain, even though they are on the same domain, the access is considered cross-site scripting. Therefore, retrieving the URL of the parent page from the iframe using techniques such as:
parent.document.location parent.window.location
will result in an access denied error.
Accessing the Browser URL
While it's impossible to directly access the parent page's URL, there is a workaround to obtain the browser's URL, which is the URL of the main page. To do this:
var url = (window.location != window.parent.location) ? document.referrer : document.location.href;
This code checks if the iframe and the parent page are not on the same URL. If they are different, it uses document.referrer to get the URL of the page that linked to the iframe. Otherwise, it uses document.location.href to get the URL of the current (iframe) document.
Additional Notes
The above is the detailed content of How Can I Access the Parent URL from an Iframe on a Different Subdomain?. For more information, please follow other related articles on the PHP Chinese website!