Is the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent 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
   }
  }

Although it works perfectly, I encountered an issue when trying to include more values to compare the hostname with. My intention was to add my custom domain name like 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
   }
  }

However, this logic always returns true and ends up throwing an error. Can someone guide me on how to fix this? I only want to throw an error if the hostname does not match these specific strings but it seems to throw an error regardless of the condition. Any assistance would be greatly appreciated as I am new to coding. Thank you!

P.S. I included "localhost" for local testing before deployment to Heroku.

Answer №1

|| will result in true if at least one of the conditions is met. Consider using && for a different evaluation:

if (window.parent 
    && window.parent.location.hostname !== "app.herokuapp.com" 
    && window.parent.location.hostname !== "www.app.com"
    && window.parent.location.hostname !== "localhost")

You can also apply 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 approach ensures that every condition must be true to return true.

For more information:

Answer №2

When faced with a comprehensive answer already provided, it's beneficial to consider an alternative method. For complex statements such as this, utilizing higher-order functions can enhance readability. Conceptualize the condition in a simpler manner: "Verify if the hostname does not correspond to any of the specified strings". This approach streamlines the code and eliminates unnecessary details:

function notEqual(y) {
  return function(x) {
    return x !== y;
  };
}

var domains = ['app.herokuapp.com','www.app.com','localhost'];
var parentWin = window.parent;

if (parentWin && domains.some(notEqual(parentWin.location.hostName))) {
  ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

Dealing with a frustrating roadblock in Three.js where you encounter an "Unknown format" error while trying to work with

Greetings, I am relatively new to THREE.js and currently experimenting with loading a .FBX Object using the FBXLoader found in three/examples/jsm/loaders/FBXLoader while integrating this into React.js. Upon launching the page, I encountered an issue where ...

Expecting a declaration statement for exporting React

When attempting to export my component, I encounter an error in my editor stating export declaration statement expected Here is the code snippet: export Header from './Header/Header'; However, if I modify it like this: export {default as Head ...

The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field. Here is my HTML code: <div class="date ui-input"> <input type="text" name="dateD" [ngModel]="model.date | dat ...

Can the grunt command be executed automatically after saving code in TypeScript?

As a newcomer to FrontEnd and JavaScript coding in TypeScript, I find myself constantly needing to follow these steps after making a code change: save the code -> compile it using Grunt -> reload the webpage. It can be quite time-consuming. Is there ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

The HTML required attribute seems to be ineffective when using AJAX for form submission

Having trouble with HTML required attribute when using AJAX submission I have set the input field in a model Form to require attribute, but it doesn't seem to work with ajax. <div class="modal fade hide" id="ajax-book-model" a ...

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

Adjust the color of a DIV based on the text value retrieved from an external source

I am looking to dynamically change the text color between red and green based on a numeric value received from an external source (API). If the value is greater than or equal to 50, it should be displayed in red. If it's less than 50, then it should ...

Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for eve ...

The NestJS HttpException class will default to a status code of 201 if no specific status code is

This particular instance showcases how instantiating the HttpException class in this manner results in an exception being thrown with an undefined status, ultimately becoming a status of 201 (I presume it defaults to this status as it is associated with a ...

JavaScript form not working on submission

When my form is submitted, a function is called that successfully redirects users on desktop to either the download-confirmation or download-failure page. However, when testing on mobile devices such as iOS and iPad, the redirection does not seem to work. ...

Explanation of if-statements and the ability to read if conditions from another object such as String[] (Dynamic If)

I am dealing with a complex object named "input" that contains numerous fields, and I need to check for null values in each field. Currently, my code looks like this: if ((input.getAction().isEmpty() || input.getAction().isBlank()) || (input.getSub ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

The slider causing conflicts with widgets and content positioned below it in an HTML layout

When implementing a slider with a fade effect, there seems to be an issue with the placement of widgets on the homepage. The problem arises from the margin-top setting as when images change in the slider, the widgets clash with the slider. During the trans ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

React Native: Enhance the background with a vibrant stripe of color

I am trying to incorporate a strip of grey in the middle of my white background, but I am encountering an issue where I am unable to input any text inside it. Below is the code snippet I am working with: container: { flex: 1, justifyContent: "cent ...

Unable to initialize myModule module

An error occurred while trying to instantiate the module 'myModule': [$injector:nomod] Module 'myModule' is not available. Make sure you have spelled the module name correctly and loaded it properly. If you are registering a module, ...

Obtain the JSON data from the body of the current post request in Express.js

I have been working on retrieving the actual request body JSON in express.js but haven't been successful so far. Most of the resources I found online only show how to access the body of type ReqBody, whereas I am looking for a way to retrieve the actu ...