当我试图在Gatsby的主体上添加脚本时,我已将以下代码添加到名为Gatsby-ssr.js 的文件中
const React = require("react")
exports.onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script type="text/javascript">
{`
(function() {
var envolveChatWidgetScript = document.createElement('script');
envolveChatWidgetScript.setAttribute('data-wg-publisher', '222222');
envolveChatWidgetScript.setAttribute('data-wg-campaign', '333333');
envolveChatWidgetScript.setAttribute('src', 'https://widget.envolvetech.com/static/js/app.js');
envolveChatWidgetScript.setAttribute('data-identifier', 'my_identifier');
envolveChatWidgetScript.setAttribute('data-backend', 'https://bot-dot-envolvetech-001.appspot.com');
document.body.appendChild(envolveChatWidgetScript);
})();
`}
</script>
]);
};
但不知怎么的,它实际上在标记中是这个
<script type="text/javascript">
(function() {
var envolveChatWidgetScript = document.createElement('script');
envolveChatWidgetScript.setAttribute('data-wg-publisher', '222222');
envolveChatWidgetScript.setAttribute('data-wg-campaign', '3333333');
envolveChatWidgetScript.setAttribute('src', 'https://widget.envolvetech.com/static/js/app.js');
envolveChatWidgetScript.setAttribute('data-identifier', 'my_identifier#x27;);
envolveChatWidgetScript.setAttribute('data-backend', 'https://bot-dot-envolvetech-001.appspot.com');
document.body.appendChild(envolveChatWidgetScript);
})();
</script>
有什么想法为什么它会被翻译成那样吗?
您是否尝试过自定义html.js
?
运行:
cp .cache/default-html.js src/html.js
或者手动将default-html.js
(放置在.cache
内(复制到/src
把你的剧本放在那里。
当Gatsby构建您的网站时,如果/src
中有html.js
,它将使用它作为您网站的样板
在html.js中,您将看到所有postBodyComponents
、onPreRenderHTML
和其他自定义API。然而,在这种情况下,您将插入原始脚本,而不是允许Gatsby解析它
在阅读了几个GH线程后,我发现使用dangerouslySetInnerHTML添加脚本实际上是有效的https://github.com/gatsbyjs/gatsby/issues/11108
const React = require("react")
exports.onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script
dangerouslySetInnerHTML={{
__html:`
(function() {
var envolveChatWidgetScript = document.createElement("script");
envolveChatWidgetScript.setAttribute("data-wg-publisher", "222222");
envolveChatWidgetScript.setAttribute("data-wg-campaign", "333333");
envolveChatWidgetScript.setAttribute("src","https://widget.envolvetech.com/static/js/app.js");
envolveChatWidgetScript.setAttribute("data-identifier", "my_identifier");
envolveChatWidgetScript.setAttribute("data-backend", "https://bot-dot-envolvetech-001.appspot.com");
document.body.appendChild(envolveChatWidgetScript);
})();
`
}}
/>,
]);
};