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

Chrome扩展:JS满足条件后显示指定HTML的问题与解决

解决Chrome扩展中模板字符串嵌套反引号的语法错误问题

针对你遇到的模板字符串嵌套反引号导致的语法错误,有以下几种可行方案:

方案1:转义内层反引号

在模板字符串中,内层的反引号可以通过添加反斜杠\进行转义,让JS引擎将其识别为普通字符,而非外层模板字符串的结束符。

示例代码:

function getTargetHTML(source) {
  return `
    <div class="container">
      <div style="background-image: url(\`${source}\`);">
        <!-- 自定义HTML内容 -->
      </div>
    </div>
  `;
}

// 检测数组并替换页面内容
const targetArray = ["abc", "heru", "def"];
if (targetArray.includes("heru")) {
  const imageSource = "your-image-url-here"; // 替换为实际资源地址
  document.body.innerHTML = getTargetHTML(imageSource);
}

方案2:用普通字符串拼接替代内层模板

如果觉得转义反引号不够直观,可以把需要插入变量的样式部分单独提取,用普通字符串拼接的方式处理,避免嵌套反引号。

示例代码:

function getTargetHTML(source) {
  const bgStyle = 'background-image: url("' + source + '");';
  return `
    <div class="container">
      <div style="${bgStyle}">
        <!-- 自定义HTML内容 -->
      </div>
    </div>
  `;
}

// 检测数组并替换页面内容
const targetArray = ["abc", "heru", "def"];
if (targetArray.includes("heru")) {
  const imageSource = "your-image-url-here";
  document.body.innerHTML = getTargetHTML(imageSource);
}

方案3:简化模板变量插值(推荐)

其实url()内的参数不需要额外包裹反引号,直接插入变量即可。如果URL包含特殊字符,提前用encodeURI()编码处理即可,这样完全避免嵌套反引号的问题。

示例代码:

function getTargetHTML(source) {
  const encodedSource = encodeURI(source);
  return `
    <div class="container">
      <div style="background-image: url(${encodedSource});">
        <!-- 自定义HTML内容 -->
      </div>
    </div>
  `;
}

// 检测数组并替换页面内容
const targetArray = ["abc", "heru", "def"];
if (targetArray.includes("heru")) {
  const imageSource = "your-image-url-here";
  document.body.innerHTML = getTargetHTML(imageSource);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:07