Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
盖茨比js客户端javascript在博客文章中内联_Javascript_Webpack_Gatsby - Fatal编程技术网

盖茨比js客户端javascript在博客文章中内联

盖茨比js客户端javascript在博客文章中内联,javascript,webpack,gatsby,Javascript,Webpack,Gatsby,我正试图建立一个博客使用盖茨比JS。我在markdown中有一些帖子包含内联javascript 例如: <script>window.alert("hello");</script> window.alert(“你好”); 我使用“盖茨比服务”命令测试站点 当我通过博客的索引浏览到我的文章时。脚本未执行。在web控制台中没有错误 当在帖子页面上时。如果执行F5或ctrl-F5,则会显示“hello”警报 将站点上载到github页面后,此行为会发生变化。我无法通过F

我正试图建立一个博客使用盖茨比JS。我在markdown中有一些帖子包含内联javascript

例如:

<script>window.alert("hello");</script>
window.alert(“你好”);
我使用“盖茨比服务”命令测试站点

当我通过博客的索引浏览到我的文章时。脚本未执行。在web控制台中没有错误

当在帖子页面上时。如果执行F5或ctrl-F5,则会显示“hello”警报

将站点上载到github页面后,此行为会发生变化。我无法通过F5或通过索引导航来执行脚本。仅当我按ctrl+F5时,脚本才会执行

可以在此处找到live test博客(它显示多个警报并尝试以绘图方式加载)

检查这个问题


React的
DangerouslySetinerHTML
插入的HTML脚本将无法执行。链接的问题有一个解决方法,也许您可以使用。

前面的答案为我指明了正确的方向

我给了所有内联脚本一个属性数据。接下来,我将以下内容添加到layouts/index.jsx(不是html.jsx,因为它只在服务器端呈现)

componentDidMount(){
让scripts=window.jQuery.find(“[data my script]”)
console.log(脚本);
scripts.forEach(函数forEachScript(元素){
const script=window.jQuery(element.text();
eval(脚本);
});
}
render(){
const{children}=this.props;
返回(
(this.contentElement=contentElement)}>
//用于在笔记本中绘声绘色
//  
{children()}
);
}
}

迪恩的解决方案对我很有效。好主意!:)

不过我确实需要避免使用JQuery,所以我在这里发布了一个不依赖JQuery的版本:

componentDidMount() {

  // Allow in-line JS scripts to be run
  let scripts = document.querySelectorAll('[data-inline-script="data-inline-script"]');
  scripts.forEach(function forEachScript(element) {
    const script = element.innerHTML;
    window.eval(script);
});
这将适用于以下HTML:

<script data-inline-script="data-inline-script">
    console.log("this works");
</script>

console.log(“这项工作”);
我在一个非常基本的静态站点上使用它。老实说,我不确定我有多喜欢使用eval(),但在我的用例中它应该不会造成任何伤害

更新 尽管上面的方法确实有效,但我还需要包含一些不起作用的脚本:(这也让人感觉很不舒服

<script data-inline-script="data-inline-script">
    console.log("this works");
</script>