Cross-domain JavaScript Considerations
Because your web app and TestBox operate on different domains, there are some features in JavaScript that simply do not work.
window.top
The most notable of which is window.top
. If you also use iFrames in your product,
it is possible that you use window.top
to reach the top-most window for information.
window.top
is useful for developers since they do not know how many levels deep their iFrame
will be. Unfortunately, being inside of TestBox changes this paradigm quite a lot. window.top
will now attempt to access app.testbox.com
instad of your own domain, which will result in a
"cross-origin error." It also means you probably won't have access to the information or
functions you are looking for.
We have a two relatively simple solutions for this problem.
Helper function
You can use the following helper function:
function windowTop(win = window) {
if (win === window.top) {
return win;
}
try {
// Simply trying to access will throw an exception.
// If an exception is thrown, we have reached the top!
win.parent.location.href;
return windowTop(win.parent);
}
catch {
return win;
}
}
Instead of calling window.top
, use windowTop()
.
window.safeTop
You could also do something like this:
window.safeTop = (function(win) {
if (win === window.top) {
return win;
}
try {
// Simply trying to access will throw an exception.
// If an exception is thrown, we have reached the top!
win.parent.location.href;
return window.safeTop(win.parent);
}
catch {
return win;
}
})(window);
This provides an API similar to window.top
, allowing for a simple find/replace
with window.safeTop
.