0

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 ?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • `try { eval("import.meta"); } catch(e){ console.log( "Not supported" ); }`? Its pretty safe as long as you don't use eval for user input. – somethinghere Sep 01 '23 at 12:42
  • @somethinghere, already done, we goes to the catch when it is supported – mpromonet Sep 01 '23 at 12:44
  • 3
    `import.meta` is always a syntax error in a direct `eval()`. – Pointy Sep 01 '23 at 12:45
  • [Very likely dupe](https://stackoverflow.com/questions/44891421/detect-es6-import-compatibility) – mplungjan Sep 01 '23 at 12:49
  • 1
    @mplungjan "Very likely" is doing a lot of heavy lifting. It's related to modules, sure, but not exactly on how to work with the meta path in non-module environments. – somethinghere Sep 01 '23 at 12:52
  • 2
    @somethinghere which is why I did not hammerclose. I would hazard a guess that most environments that supported the module supports the import and hence import.meta – mplungjan Sep 01 '23 at 12:59
  • 1
    @mplungjan unfortunately this is not the case, some browser support ` – mpromonet Sep 01 '23 at 13:05
  • 1
    @mplungjan `import` is not considered an object and `import.meta` is not considered a property access. They are special syntax. – VLAZ Sep 01 '23 at 13:16
  • Yeah, I just tried. `let bla = import.meta?.bla || null;` works, but `let bla = import?.bla || null;` give error on the optional chaining – mplungjan Sep 01 '23 at 13:19
  • 1
    @mplungjan this was my first try, before try/catch, this was working on browser supporting import.meta and raise syntaxerror on browser that did not. – mpromonet Sep 01 '23 at 13:22

0 Answers0