【问题标题】:Does Google Tag Manager execute document.write on custom HTML tags?Google 跟踪代码管理器是否在自定义 HTML 标记上执行 document.write?
【发布时间】:2018-07-18 17:39:53
【问题描述】:
【问题讨论】:
标签:
javascript
google-tag-manager
【解决方案1】:
GTM 实际上覆盖了 document.write 执行标签的范围(一个自定义的 HTML 标签,支持 document.write,就像你提到的那样),你可以在 Chrome 的 devtools 控制台上看到:
document.write
function (){return m(g(arguments).join(""))} gtm.js?id=GTM-someid:formatted:1455
一旦 GTM 完成了 document.write 调用,它就会丢弃覆盖:
document.write
function write() { [native code] }
它提供的实现使用“普通”插入(例如 document.createElement 后跟 appendChild 或 insertBefore)和一个在脚本加载时运行的侦听器(例如 onreadystatechange 或 onload)并执行放在 document.write 之后的代码调用标签定义。
【解决方案3】:
我必须在一个项目中实现类似的功能。从谷歌标签管理器查看缩小的 js 后,我发现他们正在使用这个库:
https://github.com/krux/postscribe
GTM 做了一些聪明的事
确实很聪明:)
快速 es6 示例:
import postscribe from 'postscribe'
const customHtml = "<script>document.write('hello')</script>"
const div = document.createElement('div')
div.style.display = 'none'
div.style.visibility = 'hidden'
document.body.appendChild(div)
postscribe(div, customHtml)