简体   繁体   English

在 React Helmet/ Gatsby 中插入自定义脚本

[英]Inserting a Custom Script in React Helmet/ Gatsby

I have this custom script that from a third party I am trying to embed into React Helmet我有这个来自第三方的自定义脚本,我试图将它嵌入到 React Helmet 中

Usually the scripts are given only as a src url.通常脚本仅作为 src url 给出。 If I am given the code below, what is the best practice to embed the embed the script with React Helmet如果给我下面的代码,使用 React Helmet 嵌入脚本的最佳实践是什么

    <script>
document.getElementsByTagName('head')[0].appendChild(function(s){
    var d=document,m2g=d.createElement('script'),l=function(){Mobi2Go.load(s.container,s.ready);},jq=window.jQuery&&+window.jQuery.fn.jquery.replace(/^(\d+).*$/,'$1')===1&&+window.jQuery.fn.jquery.replace(/^\d+\.(\d+).*$/,'$1')>=7,qs=window.location.search.substring(1),re='=(.*?)(?:;|$)',c=d.cookie.match('MOBI2GO_SESSIONID'+re),w=window.innerWidth;
    m2g.src='https://www.mobi2go.com/store/embed/1990-v8oL.js?'+qs+(jq?'&no_jquery':'')+(c?'&s='+c[1]:'')+'&device_width='+w;
    if(m2g.onload!==undefined)m2g.onload=l;else m2g.onreadystatechange=function(){if(m2g.readyState!=='loaded'&&m2g.readyState!=='complete')return;m2g.onreadystatechange=null;l();}
    window.Mobi2Go_est = +(new Date);
    return m2g;
}({
    container: 'Mobi2Go-Storefront', // Replace with ID  of the element to inject UI into
    ready: function() {} // Callback to fire when app is ready
}));
</script>

There is obviously errors if I include all of that in the React Helmet Not sure what is the best practice to make it work.如果我将所有这些都包含在 React Helmet 中,显然会出现错误。不确定使其工作的最佳实践是什么。

I have also tried placing it in the html.js file in gatsby我也试过把它放在 gatsby 的 html.js 文件中

 import React from 'react';
import PropTypes from 'prop-types';

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
      <script
        dangerouslySetInnerHTML={{
          __html: `
          document.getElementsByTagName('head')[0].appendChild(function(s){
            var d=document,m2g=d.createElement('script'),l=function(){Mobi2Go.load(s.container,s.ready);},jq=window.jQuery&&+window.jQuery.fn.jquery.replace(/^(\d+).*$/,'$1')===1&&+window.jQuery.fn.jquery.replace(/^\d+\.(\d+).*$/,'$1')>=7,qs=window.location.search.substring(1),re='=(.*?)(?:;|$)',c=d.cookie.match('MOBI2GO_SESSIONID'+re),w=window.innerWidth;
            m2g.src='https://www.mobi2go.com/store/embed/1990-v8oL.js?'+qs+(jq?'&no_jquery':'')+(c?'&s='+c[1]:'')+'&device_width='+w;
            if(m2g.onload!==undefined)m2g.onload=l;else m2g.onreadystatechange=function(){if(m2g.readyState!=='loaded'&&m2g.readyState!=='complete')return;m2g.onreadystatechange=null;l();}
            window.Mobi2Go_est = +(new Date);
            return m2g;
        }({
            container: 'Mobi2Go-Storefront', // Replace with ID  of the element to inject UI into
            ready: function() {} // Callback to fire when app is ready
        })););
        `,
        }}
      />
    </html>
  );
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
};

It should work using react-helmet , there are examples of it in the README .它应该使用react-helmet工作,在README中有它的例子。

You might be missing type="text/javascript" in your script tag:您的script标签中可能缺少type="text/javascript"

<script type="text/javascript">
  // your script goes here
</script>

Al alternative option if this doesn't work for you is to customize Gatsby's html.js .如果这对您不起作用,另一种选择是自定义 Gatsby 的 html.js

Use the script tag inside the helmet tag.使用头盔标签内的脚本标签。 Most important your script should me inside the curly braces最重要的是你的脚本应该在花括号内

 <Helmet> <script> {`alert( 'Hello, world;' );`} </script> </Helmet>

gatsby-react-helmet 生成空<title>在 SSR 上&lt;/div&gt;</title><div id="text_translate"><p> 我的 Gatsby 网站没有在 SSR 上生成正确的标题标签。 当我建立网站时,我在生成的文件上得到的只是&lt;title data-react-helmet="true"&gt;&lt;/title&gt; 。 我很感激帮助找到问题并解决,因为经过长时间的调试过程,我不知道哪个可能是问题。</p><p> 相关文件:</p><p> <strong>package.json</strong></p><pre> ... "dependencies": { "gatsby": "^2.19.45", "gatsby-image": "^2.2.44", "gatsby-plugin-manifest": "^2.2.48", "gatsby-plugin-react-helmet": "^3.2.2", "gatsby-plugin-sharp": "^2.4.13", "gatsby-plugin-sitemap": "^2.3.1", "gatsby-plugin-typescript": "^2.3.3", "gatsby-source-filesystem": "^2.1.56", "gatsby-source-graphql": "^2.2.0", "react": "^16.12.0", "react-dom": "^16.12.0", "react-helmet": "^6.0.0", }...</pre><p> <strong>gatsby.config.js</strong></p><pre> plugins: [ `gatsby-plugin-react-helmet`, ... ]</pre><p> <em>(gatsby-plugin-offline 已禁用)</em></p><p> 搜索引擎优化</p><pre>import React from "react" import { Helmet } from "react-helmet" import { useStaticQuery, graphql } from "gatsby" interface Props { title: string description?: string image?: string } const SEO = ({ title, description, image }: Props) =&gt; { const { site } = useStaticQuery( graphql` query { site { siteMetadata { title description image siteUrl } } } ` ) const metaDescription = description || site.siteMetadata.description const shareImage = image || site.siteMetadata.image const url = site.siteMetadata.siteUrl return ( &lt;Helmet defer={false}&gt; &lt;title&gt;{title}&lt;/title&gt; &lt;meta name="description" content={metaDescription} /&gt; &lt;meta name="image" content={shareImage} /&gt; &lt;link rel="canonical" href={url} /&gt; &lt;meta property="og:url" content={url} /&gt; &lt;meta property="og:type" content="website" /&gt; &lt;meta property="og:title" content={title} /&gt; &lt;meta property="og:description" content={metaDescription} /&gt; &lt;meta property="og:image" content={shareImage} /&gt; &lt;meta name="twitter:card" content="summary_large_image" /&gt; &lt;meta name="twitter:title" content={title} /&gt; &lt;meta name="twitter:description" content={metaDescription} /&gt; &lt;meta name="twitter:image" content={shareImage} /&gt; &lt;/Helmet&gt; ) } export default SEO</pre><p> 将&lt;title&gt;{title}&lt;/title&gt;更改为&lt;Helmet title={title}&gt;或删除defer={true}不会改变结果中的任何内容。</p><p> <strong>盖茨比-ssr.js</strong></p><pre> import React from "react" import { Helmet } from "react-helmet" export const onRenderBody = ( { setHeadComponents, setHtmlAttributes, setBodyAttributes }, pluginOptions ) =&gt; { const helmet = Helmet.renderStatic() setHtmlAttributes(helmet.htmlAttributes.toComponent()) setBodyAttributes(helmet.bodyAttributes.toComponent()) setHeadComponents([ helmet.title.toComponent(), helmet.link.toComponent(), helmet.meta.toComponent(), helmet.noscript.toComponent(), helmet.script.toComponent(), helmet.style.toComponent() ]) }</pre><p> <em>我仍然有一个空的 srr 文件的问题。</em></p><p> 在任何给定的页面上,我都会调用 SEO 标签,例如:</p><pre> &lt;SEO title="Hello World" description="Foo Bar" /&gt;</pre></div> - gatsby-react-helmet generating empty <title> on SSR

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 包含 gatsby 头盔脚本 - Include gatsby helmet script Gatsby 在 react-helmet 中嵌入带有脚本标签的表单 - Gatsby embed forms with script tag in react-helmet Gatsby/React 项目不会重新识别 ssr 脚本标签 cloudinary 变量也尝试使用 Helmet - Gatsby/React Project wont recongnize ssr script tag cloudinary variable also tried with Helmet 使用头盔向 Gatsby 添加脚本标签会引发语法错误 - Adding script tag to Gatsby using helmet throws syntax errors Gatsby 网站,使用头盔请求第一页时脚本不可用 - Gatsby site, Script not available on first page request with Helmet gatsby-react-helmet 生成空<title>在 SSR 上&lt;/div&gt;</title><div id="text_translate"><p> 我的 Gatsby 网站没有在 SSR 上生成正确的标题标签。 当我建立网站时,我在生成的文件上得到的只是&lt;title data-react-helmet="true"&gt;&lt;/title&gt; 。 我很感激帮助找到问题并解决,因为经过长时间的调试过程,我不知道哪个可能是问题。</p><p> 相关文件:</p><p> <strong>package.json</strong></p><pre> ... "dependencies": { "gatsby": "^2.19.45", "gatsby-image": "^2.2.44", "gatsby-plugin-manifest": "^2.2.48", "gatsby-plugin-react-helmet": "^3.2.2", "gatsby-plugin-sharp": "^2.4.13", "gatsby-plugin-sitemap": "^2.3.1", "gatsby-plugin-typescript": "^2.3.3", "gatsby-source-filesystem": "^2.1.56", "gatsby-source-graphql": "^2.2.0", "react": "^16.12.0", "react-dom": "^16.12.0", "react-helmet": "^6.0.0", }...</pre><p> <strong>gatsby.config.js</strong></p><pre> plugins: [ `gatsby-plugin-react-helmet`, ... ]</pre><p> <em>(gatsby-plugin-offline 已禁用)</em></p><p> 搜索引擎优化</p><pre>import React from "react" import { Helmet } from "react-helmet" import { useStaticQuery, graphql } from "gatsby" interface Props { title: string description?: string image?: string } const SEO = ({ title, description, image }: Props) =&gt; { const { site } = useStaticQuery( graphql` query { site { siteMetadata { title description image siteUrl } } } ` ) const metaDescription = description || site.siteMetadata.description const shareImage = image || site.siteMetadata.image const url = site.siteMetadata.siteUrl return ( &lt;Helmet defer={false}&gt; &lt;title&gt;{title}&lt;/title&gt; &lt;meta name="description" content={metaDescription} /&gt; &lt;meta name="image" content={shareImage} /&gt; &lt;link rel="canonical" href={url} /&gt; &lt;meta property="og:url" content={url} /&gt; &lt;meta property="og:type" content="website" /&gt; &lt;meta property="og:title" content={title} /&gt; &lt;meta property="og:description" content={metaDescription} /&gt; &lt;meta property="og:image" content={shareImage} /&gt; &lt;meta name="twitter:card" content="summary_large_image" /&gt; &lt;meta name="twitter:title" content={title} /&gt; &lt;meta name="twitter:description" content={metaDescription} /&gt; &lt;meta name="twitter:image" content={shareImage} /&gt; &lt;/Helmet&gt; ) } export default SEO</pre><p> 将&lt;title&gt;{title}&lt;/title&gt;更改为&lt;Helmet title={title}&gt;或删除defer={true}不会改变结果中的任何内容。</p><p> <strong>盖茨比-ssr.js</strong></p><pre> import React from "react" import { Helmet } from "react-helmet" export const onRenderBody = ( { setHeadComponents, setHtmlAttributes, setBodyAttributes }, pluginOptions ) =&gt; { const helmet = Helmet.renderStatic() setHtmlAttributes(helmet.htmlAttributes.toComponent()) setBodyAttributes(helmet.bodyAttributes.toComponent()) setHeadComponents([ helmet.title.toComponent(), helmet.link.toComponent(), helmet.meta.toComponent(), helmet.noscript.toComponent(), helmet.script.toComponent(), helmet.style.toComponent() ]) }</pre><p> <em>我仍然有一个空的 srr 文件的问题。</em></p><p> 在任何给定的页面上,我都会调用 SEO 标签,例如:</p><pre> &lt;SEO title="Hello World" description="Foo Bar" /&gt;</pre></div> - gatsby-react-helmet generating empty <title> on SSR 错误:无法找到插件“gatsby-plugin-React-helmet” - Error: Unable to find plugin "gatsby-plugin-React-helmet" 在页面加载反应头盔后运行或执行脚本,反应 gatsbyjs - Run or execute script after page is loaded with react helmet, react gatsbyjs 将 react-helmet 添加到我的 Gatsby 项目中会导致错误:元素类型无效 - Adding react-helmet into my Gatsby project causes an error: Element type is invalid 延迟反应组件加载,直到头盔头部脚本加载 - Delaying react component load until helmet head script loads
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM