You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Home Assistant中导入Yandex地图JS文件报错,求解决方案

问题:Home Assistant自定义UI中导入Yandex Maps JS库报错

按照Home Assistant官方文档的方式导入Yandex Maps的JavaScript库:

import "https://api-maps.yandex.ru/2.1/?apikey=1&module";

执行时出现以下错误:

?lang=ru_RU&apikey=1&module:1 Uncaught TypeError: Cannot read properties of undefined (reading 'performance')
at ymapsInit (?lang=ru_RU&apikey=1&module:1:84)
at ?lang=ru_RU&apikey=1&module:1:28837

报错指向Yandex库中的这段代码:

(function ymapsInit(e) {
    var n = this
      , t = {
        ns: {},
        supports: {},
        env: e
    };
    t.performance = {
        now: n.performance && n.performance.now ? n.performance.now.bind(n.performance) : function() {
            return Date.now()
        }
    },

该库在Home Assistant外部环境可正常运行,但在自定义UI中无法使用,且无法修改外部库代码,求解决方法。

解决方案

原因分析

Home Assistant的自定义UI以ES模块方式运行,模块作用域中this的值为undefined;而Yandex Maps的代码默认期望this指向全局对象(浏览器中的window),因此尝试读取n.performance时会触发undefined的属性读取错误。在普通浏览器环境中,脚本运行在全局上下文,this默认指向window,所以不会出现问题。

解决方法:改用动态创建script标签加载库

替换原有的import语句,通过动态创建<script>标签的方式加载Yandex Maps库,让脚本在全局上下文执行,确保this指向window:

// 移除原import语句,替换为以下代码
const ymapsScript = document.createElement('script');
// 替换为你的实际API密钥和需要的模块
ymapsScript.src = 'https://api-maps.yandex.ru/2.1/?apikey=你的API密钥&module=你需要的模块';
// 脚本加载完成后初始化地图
ymapsScript.onload = () => {
  ymaps.ready(() => {
    // 在这里编写你的地图初始化逻辑
    // 示例:创建地图实例
    // const map = new ymaps.Map('map-container', { ... });
  });
};
document.head.appendChild(ymapsScript);

注意事项

  • 确保你的自定义card中存在地图容器元素(比如带id="map-container"的<div>),用于挂载地图实例。
  • 替换代码中的API密钥和模块参数为你的实际配置。

内容的提问来源于stack exchange,提问作者LA_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:13:36