There are various methods to embed tweets - as per the documentation on embedding tweets:
Our widget scans the DOM during execution, converting blockquote.twitter-tweet
elements into fully-rendered embedded Tweets based on their content.
To directly render an embedded Tweet at runtime, you can use the twttr.widgets.createTweet()
function.
a) Using Default Publish Widget
If you process this tweet through the publish widget, it will generate the following code (demo):
<blockquote class="twitter-tweet">
<p lang="en" dir="ltr">Nobody:<br><br>Software Marketing Page: "Blazingly Fast"</p>
— Kyle Mitofsky (@KyleMitBTV)
<a href="https://twitter.com/KyleMitBTV/status/1188837207206977536">October 28, 2019</a>
</blockquote>
<script src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
You could then locate all the <twitter-widget>
elements that were created and update style properties within their shadowRoot
like this:
[...document.getElementsByTagName('twitter-widget')].forEach(tweet => {
let style = tweet.shadowRoot.firstElementChild;
let css = document.createTextNode(`.EmbeddedTweet .CallToAction { display: none; }`);
style.appendChild(css);
})
However, we need to wait for the widget to process each tweet, and there is no direct event to trigger this action at the right time (without resorting to using a setTimeout
).
b) Manual JavaScript Implementation
You can customize the creation of the tweet manually like this:
let tweetId = "1188837207206977536"
let tweetContainer = document.getElementById('tweet-container');
twttr.widgets.createTweet(tweetId, tweetContainer)
This will return a promise that allows you to handle the tweet insertion and update styles in the shadowRoot
accordingly (demo):
<div id="tweet-container" class="embedded-tweets"></div>
<script src="https://platform.twitter.com/widgets.js"></script>
<script type="text/javascript">
let tweetId = "1188837207206977536"
let tweetContainer = document.getElementById('tweet-container');
twttr.widgets.createTweet(tweetId, tweetContainer)
.then(function (tweet) {
let style = tweet.shadowRoot.firstElementChild;
let css = document.createTextNode(`.EmbeddedTweet .CallToAction { display: none; }`);
style.appendChild(css);
});
</script>
Note: The Tweet ID must be a string as numbers above
2<sup>53</sup> - 1 = 9007199254740991
in JavaScript will be truncated (Number.MAX_SAFE_INTEGER
)
Insights on Shadow DOM
The <twitter-widget>
is a web component styled using the shadow DOM. Global style overrides using /deep/
or ::shadow
were deprecated in Chrome 45 and removed in Chrome 63. Presently, setting a style
element directly in the element's shadowRoot
is the recommended approach to override styles in the shadow root.