如何检测浏览器是否支持import.meta?解决语法报错问题
检测浏览器对
import.meta的支持并实现兼容方案 在浏览器环境中,我们可以通过import.meta.url获取当前脚本的URI,示例代码如下:
let currentPath = import.meta.url.substring( 0, import.meta.url.lastIndexOf("/"));
这段代码在现代浏览器中可正常运行,但旧版浏览器会直接抛出SyntaxError。尝试用try-catch包裹代码无法解决问题——因为语法错误是在代码解析阶段触发的,而非运行时,try-catch无法捕获这类错误。
可行解决方案
核心思路是利用new Function()延迟代码解析:new Function内部的代码会在运行时才被解析,不会影响主代码的解析流程,此时try-catch就能正常捕获不支持import.meta时的错误。
方案一:先检测再执行
let currentPath; // 检测浏览器是否支持import.meta const supportsImportMeta = (() => { try { return new Function('return import.meta')() !== undefined; } catch (e) { return false; } })(); if (supportsImportMeta) { currentPath = import.meta.url.substring(0, import.meta.url.lastIndexOf("/")); } else { currentPath = location.href.substring(0, location.href.lastIndexOf("/")); }
方案二:直接在try中通过new Function获取路径
let currentPath; try { currentPath = new Function('return import.meta.url.substring(0, import.meta.url.lastIndexOf("/"))')(); } catch (e) { currentPath = location.href.substring(0, location.href.lastIndexOf("/")); }
内容的提问来源于stack exchange,提问作者mpromonet
相关产品推荐
相关产品推荐

