Reputation: 35
I have this bit of code to protect my page from being iframed.
window.onload = function(){
try
{
if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){
throw new Error();
}
catch (e){
//do something
}
}
It works perfectly fine until I try to add more values to compare the hostname with. I want to add my custom domain name. I tried this:
window.onload = function(){
try
{
if (window.parent && (window.parent.location.hostname !=="app.herokuapp.com"
|| window.parent.location.hostname !== "www.app.com"
|| window.parent.location.hostname !== "localhost")){
throw new Error();
}
catch (e){
//do something
}
}
This always returns true and therefore throws an error. How can I make this work? Unless the hostname matches these strings, I want to throw an error and it throws an error no matter what. I am new at this and would love some help! Thanks.
Ps. I added "localhost" because I want to be able to test it locally before pushing to heroku.
Upvotes: 1
Views: 1685
Reputation: 94101
Since there's already a pretty complete answer I would suggest a different approach. When you have long statements like that, I find that working with higher-order functions is easier to read. Think of your condition this way: "Check if the hostname doesn't match any of the given strings". That's how I would like to read the code, everything else is boilerplate:
function not(y) {
return function(x) {
return x !== y;
};
}
var hosts = ['app.herokuapp.com','www.app.com','localhost'];
var parent = window.parent;
if (parent && hosts.some(not(parent.location.hostName))) {
...
}
Upvotes: 0
Reputation: 149000
||
returns evaluates to true
if any of the operands evaluate to true
. Perhaps you meant to use &&
instead:
if (window.parent
&& window.parent.location.hostname !== "app.herokuapp.com"
&& window.parent.location.hostname !== "www.app.com"
&& window.parent.location.hostname !== "localhost")
Or by De Morgan's Law:
if (window.parent
&& !(window.parent.location.hostname === "app.herokuapp.com"
|| window.parent.location.hostname === "www.app.com"
|| window.parent.location.hostname === "localhost"))
This will evaluate to true
if all of the operands evaluate to true
.
Further Reading
Upvotes: 6