How to detect if import.meta is supported by a browser?
06:05 01 Sep 2023

In JavaScript running in a browser, to get the current script URI, one can write like in https://stackoverflow.com/a/57364525/3102264:

let currentPath = import.meta.url.substring(
  0, import.meta.url.lastIndexOf("/"));

This works fine in a modern browser, however in an old browser it raises a SyntaxError.

I would like to detect if import.meta is supported in order to use location.href when it is not available.

I tried using try catch like

let currentPath;
try {
  currentPath  = import.meta.url.substring(
    0, import.meta.url.lastIndexOf("/"));
}
catch(e) {
  currentPath  = location.href.substring(
    0, location.href.lastIndexOf("/"));
}

But this is not working, it still throws

Uncaught SyntaxError Unexpected token import

Is there a way to make conditional code depending on import.meta support?

Note: using location.href is an acceptable fallback when served from same based url (even it did not solve what allow import.meta)

javascript es6-modules browser-feature-detection