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

如何使用JavaScript向body中插入包含配置变量的特殊script脚本

实现方法

你需要插入的脚本分为内联配置段、外部资源加载段两部分,有两种常用实现方案:

方案1(推荐):分别创建脚本节点插入

这种方式兼容性更强,不存在特殊字符转义风险,代码示例如下:

// 插入配置段内联脚本
const configScript = document.createElement('script');
configScript.type = 'text/javascript';
configScript.textContent = `
var _iub = _iub || [];
_iub.csConfiguration = {
    "countryDetection": true,
    "reloadOnConsent": true,
    "consentOnContinuedBrowsing": false,
    "perPurposeConsent": true,
    "purposes": "1,2,3,4,5",
    "lang": "en",
    "siteId": xxxx, // 替换为你的实际站点ID
    "cookiePolicyId": 494xxxx, // 替换为你的实际Cookie政策ID
    "cookiePolicyUrl": "https://www.iubenda.com/privacy-policy/xxxx", // 替换为你的实际政策页地址
    "banner": {
        "acceptButtonDisplay": true,
        "customizeButtonDisplay": true,
        "rejectButtonDisplay": true,
        "position": "float-bottom-center",
        "backgroundOverlay": true
    }
};
`;
document.body.appendChild(configScript);

// 插入外部资源加载脚本
const loaderScript = document.createElement('script');
loaderScript.type = 'text/javascript';
loaderScript.src = '//cdn.iubenda.com/cs/iubenda_cs.js';
loaderScript.charset = 'UTF-8';
loaderScript.async = true;
document.body.appendChild(loaderScript);

方案2:直接插入HTML片段

写法更简洁,适合快速实现,代码示例如下:

document.body.insertAdjacentHTML('beforeend', `
<script type="text/javascript">
var _iub = _iub || [];
_iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }};
</script>
<script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
`);

注意事项

两种方案都需要先把代码中的xxxx占位符替换为你自己的实际业务参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:54:00