Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - React JS how to get script inside dangerouslySetInnerHTML executed

How to get script inside dangerouslySetInnerHTML get executed?

class Page extends Component {

  render() {
    return (
      <script
        dangerouslySetInnerHTML={{ __html: `
          console.log('hello world');
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({
            event: 'viewCart'
          });
        ` }}
      />
    );
  }
}

I can't get console.log('hello world') executed. Anybody can help? Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Script elements don't get executed because of the way that react-dom creates them.

When ReactDOM.createElement receives a type of 'script' it uses .innerHTML instead of using document.createElement like you might expect.

var div = document.createElement('div');
div.innerHTML = '<script></script>';

var element = div.removeChild(div.firstChild);

Creating the script in this way sets the "parser-inserted" flag on that element to true. This flag tells the browser that it should not execute.


https://github.com/facebook/react/blob/c2a2d8a539bf02e40c43d36adc2826e228f30955/packages/react-dom/src/client/ReactDOMComponent.js#L406

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations

https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...