Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one.

The issue arises when the Angular compiler (which I suspect is actually tsc behavior) transpiles all code to the targeted ES version (in this case es6), causing the check for optional chaining support to break during runtime:

export function isOpChainingSupported(): boolean {
  const opChainingChecker = {
    support: true
  };
  try {
    // CODE BEFORE TRANSPILING:
    // return opChainingChecker?.support;
    //
    // TURNS INTO
    return
      opChainingChecker === null || opChainingChecker === void 0 ? 
      void 0 :
      opChainingChecker.support;
  } catch {
    return false;
  }
}

I attempted to move this code to a separate function in a plain JavaScript file and used the 'allowJs' TS config to import it without errors...unfortunately, tsc still transpiled it.

At this point, I see three options, none of which are ideal:

  • Using eval('constObj?.prop'), which poses security risks based on various sources I've consulted;
  • Loading my plain JavaScript file dynamically as an asset;
  • Creating an ES utility library specifically for this function (currently leaning towards this option, although it may be overkill for my situation).

My question is: Is there a simpler solution that I may have overlooked? Any input or alternative approach would be greatly appreciated!

Apologies in advance if this question seems trivial, but sometimes seeking fresh perspectives can lead to unexpected solutions!

Cheers!

Answer №1

After exploring one of the options mentioned in the question, I decided to share my approach.

Initially, I experimented with a "third party library" solution, which unfortunately failed due to syntax errors that caused exceptions before the code execution by the browser. This led to two outcomes:

  • The try/catch block couldn't catch the exception;
  • The current "execution context" was abruptly terminated.

To prevent my app from crashing and ensure error checking capability, I needed a method to execute the "checker code" separately from the main thread.

Ultimately, I merged elements from multiple solutions to create a specialized library. This library loads a basic script to test optional chaining support, returning a Promise with a boolean indicating browser compatibility.

The dynamic loading of the script involves adding a temporary script tag to isolate execution from the main context and avoid SyntaxError-related crashes. The integrity attribute is utilized for enhanced security.

If anyone encounters similar challenges, they can implement my solution by installing the npm package optional-chaining-checker and following the provided instructions. While I aimed for customization, users can explore my repository to modify the code according to their preferences!

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

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

Error in Discord JS: Unable to access undefined properties (roles)

Currently, I am in the process of developing an event that will periodically check a MongoDB database for any expired keys and then proceed to remove a specific role from the corresponding member. const mongoose = require("mongoose") const { Disc ...

Issue with Angular 6: Struggling to Implement DatePipe

I am trying to set the current date within a formGroup in a specific format, but I keep encountering an error with the code below: 'Unable to convert "13/07/2020" into a date' for pipe 'DatePipe' this.fb.group({ startdateActivi ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Automatically fill in form fields with data from a JSON file as soon as the user enters a value

How can I retrieve the bank name, branch, city, and district from a JSON array? Below is the contents of my results.json file: { "ifsc": [{ "ifsc": "PUNB0000100", "bank": "PUNJAB NATIONAL BANK", "city": "ABOHAR ...

What is the best way for my web application to interface with a serial port?

I am working on a cloud-based web application that uses ASP Web API and Angular, both hosted on Azure. I have a requirement for my Angular app to communicate with a serial port for reading and writing data. How can I achieve this functionality? I've ...

Using ngModel to Enhance Ionic Forms

I've encountered an issue with mapping a form to a model object. Once I include [[ngModel]] in the ion-input, the page fails to load without any errors. html <ion-input type="text" [(ngModel)]="personModel.username" formControlName="username" id= ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

"Reasons Why I'm Unable to Retrieve the Length of an Array

Can someone lend a hand with finding the array length? I attempted to utilize Object.keys for this task { "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#sites('volagas.sharepoint.com')/sites('volagas.sharepoint.com%2C9 ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Enhance click functionality on list item content using knockoutjs

Check out my app on GitHub or view it live at this link. I'm trying to implement a feature where clicking on each item, like "Bookworm Buddy," will toggle its description within the project. Here's what I've attempted so far: function AppV ...

How One Simple Click Can Impact Every Button in jQuery Ajax操作

Whenever I try to click a button that should only affect a specific id, it ends up affecting every button on the page by sending data to our API as well. You can check out a snapshot of my page here. Each row has a unique id, but when I click the vote butt ...

ExpressJS refuses to wait for my promise to be fulfilled

I'm in the process of creating a search-page on my server. Whenever the endpoint is accessed and the user waits for the search function to deliver the results and display them on the page, Express somehow redirects to the 404 handler instead. An error ...

Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself? Upon form submission, I pass the form as a parameter to a custom function: <form #myForm="ngForm" ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Guide on implementing a cordova plugin in a TypeScript cordova application

In my Cordova project, which utilizes Angular and Typescript, I am facing issues with implementing the juspay-ec-sdk-plugin for Cordova. I have explored possible solutions on StackOverflow related to integrating Cordova plugin in an Angular 4 Typescript ...

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...