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

如何在Angular页面的head标签中按域名条件注入Hotjar脚本

Angular 条件动态注入脚本到head的实现方案

推荐使用Angular内置的DOCUMENT注入令牌操作DOM,相比直接调用全局document兼容性更好,也适配服务端渲染等特殊场景。

实现步骤

  1. 在根组件(通常为app.component.ts)中注入DOCUMENT对象
  2. 在ngOnInit初始化钩子中添加域名判断逻辑
  3. 域名匹配时执行脚本注入逻辑

完整代码示例

import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(@Inject(DOCUMENT) private document: Document) {}

  ngOnInit(): void {
    // 正式域名校验逻辑
    const OFFICIAL_ORIGIN = 'https://www.stackoverflow.com';
    if (window.origin === OFFICIAL_ORIGIN) {
      this.injectHotjarScript();
    }
  }

  private injectHotjarScript(): void {
    // 避免重复注入
    const existScript = this.document.querySelector('script[src*="hotjar"]');
    if (existScript) return;

    // 你提供的hotjar初始化逻辑
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:*******,hjsv:*}; // 替换为实际的hotjar参数
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,this.document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
  }
}

额外说明

  • 如果需要脚本更早加载,可以配合APP_INITIALIZER提供者实现,脚本会在Angular应用启动完成前完成注入
  • 不要直接在index.html的静态脚本中写判断逻辑,会导致服务端渲染、预渲染场景下全局对象访问报错
  • 如果需要更换注入的脚本,只需要修改injectHotjarScript中的脚本创建逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:06:02