I would like to create a method that returns an iframe's URL if the parent page is allowed to (because it is under the same domain), and return a falsy value if the parent page is not allowed to do so.
I have the following code hosted by https://cjshayward.com:
<!DOCTYPE html> <html><head></head><body> <iframe name="test_frame" id="test_frame" src="https://cjshayward.com"></iframe><script> setTimeout(function() { try { console.log(window.frames.testframe.location.href); } catch(error) { console.log('Not able to load.'); }); }, 1000);</script></body></html>
The setTimeout()
is used because if I specify an iframe and then immediately have JavaScript attempt to load the page's URL, it will load a URL of about:blank
.
But when I change the URL to the script in the same place to another domain (that has no restrictions on e.g. loading contents in a frame), Firefox logs the string specified in the catch block, and still logs an uncaught DOMException:
<!DOCTYPE html> <html><head></head><body> <iframe name="test_frame" id="test_frame" src="https://orthodoxchurchfathers.com"></iframe><script> setTimeout(function() { try { console.log(window.frames.testframe.location.href); } catch(error) { console.log('Not able to load.'); }); }, 1000);</script></body></html>
In the first case, it logs https://cjshayward.com. In the second case, it logs "Not able to load," but still shows an uncaught DOMException in the log.
How can I make a function that returns the iframe's location.href if it is available, and returns something falsy like an empty string if the same is not available due to browser security restrictions?
Or, taking a slight step back, is the logged DOMException unimportant? If I replace the console.log() calls with return calls from within a function, will my code be able to use the return value as the iframe's URL if such is available and a falsy value if it is not available?
TIA,