Sunday, 3 September 2023

How to detect if import.meta is supported by a browser

In a javascript running in a browser to get the current script uri, like in https://stackoverflow.com/a/57364525/3102264, the code is

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

This is working fine on nowdays browser, however on 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 throw

Uncaught SyntaxError Unexpected token import

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



from How to detect if import.meta is supported by a browser

No comments:

Post a Comment