如何在Next.js AMP页面的窗口对象中添加值

问题描述 投票:0回答:1

我正在尝试向Next.js AMP页面中的GA跟踪的窗口对象添加值。但是我无法编辑窗口对象。

See code snippet here

import Head from 'next/head';

import React, { Component } from 'react';

import get from 'lodash/get';

import styles from './styles';

export default class AMPHeader extends Component {

render() {

`let contentData;`
`for (const key in this.props) {`
  `if (this.props[key].templateTitle === 'mainNavigation') {`
    `contentData = this.props[key];`
    `break;`
  `}`
`}`

return (

  `<>`

    `<Head>`
      `<script`
        `async`
        `custom-element="amp-sidebar"`
        `src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"`
      `></script>`
      `<script`
        `async`
        `custom-element="amp-script"`
        `src="https://cdn.ampproject.org/v0/amp-script-0.1.js"`
      `></script>`
    `</Head>`

    `<amp-script layout="container" src="https://example.com/hello-world.js">`
      `<button>Hello amp-script!</button>`
    `</amp-script>`

    `<script id="hello-world" type="text/plain" target="amp-script">`
      `{(window.test = 'Test')}`
    `</script>`
reactjs amp-html next.js
1个回答
0
投票

反应转义的内部HTML。为此,您必须使用dangerouslySetInnerHTML属性。

[通常,通过代码设置HTML是有风险的,因为它很容易不经意间将您的用户暴露于跨站点脚本(XSS)攻击。因此,您可以直接从React设置HTML,但是您必须输入危险地设置SetInnerHTML并将带有__html键的对象传递给提醒自己这很危险。例如:

<script
  id="hello-world"
  type="text/plain"
  target="amp-script"
  dangerouslySetInnerHTML={{
    __html: JSON.stringify({
      window: {
        test: 'test',
      },
    }),
  }}
></script>

© www.soinside.com 2019 - 2024. All rights reserved.