简体   繁体   中英

React dangerouslySetInnerHTML and script tag

I'm building a React application that use to deal with remote HTML content.

In fact, we're using a backoffice with WYSIWYG stuff, and so I need to retrieve that in my react app.

It works great for "standard" stuff, such as <p> , <div> etc...

Actually, I wanted to create content based on twitter, like embedding a timeline of tweets in a page of my application.

Here's the HTML I m getting from the backend API :

<div>
  <a class="twitter-timeline" href="https://twitter.com/twitterAccount">Tweets by Twitter Account</a>
  <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

Nothing more / less than the embedding stuff provided by twitter to make that work.

When I try to put it in :

<div dangerouslySetInnerHTML={content}/>

It doesn't provide anything on the screen (except the link), but not the timeline, just like if (and I m sure it's because of that) the script tag isn't executed.

However, the stuff is present in my DOM and really looks like :

<div>
  <a class="twitter-timeline" href="https://twitter.com/user">Tweets by User</a><br>
  <script async="" src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

Does it exist a way to make that script executed?

You could read the src attribute in the script tag, do a request with the url and once loaded eval() the text, but this is far from recommended.

Do you always expect the same script tag to appear in the html? perhaps including

<script async="" src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

in your page would work fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM