Notes

Change embedded tweet dark theme to match site


Luke Lowrey
Luke Lowrey
- 1 min read

My custom Ghost theme uses a typical CSS/JS dark mode toggle. One thing I found jarring was embedded tweets not updating to the new theme.

I put together this hack javascript (because I could find no better approach) that waits until (hopefully) the tweet has loaded then updates the URL to the proper theme.

var storedTheme = localStorage.getItem('theme') || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");

setTimeout(function() {
    var targetTheme = storedTheme == "dark" ? "light" : "dark";
    switchTweetTheme(targetTheme, storedTheme);
}, 1000);

function switchTweetTheme(currentTheme, targetTheme) {
    var tweets = document.querySelectorAll('[data-tweet-id]');

    tweets.forEach(function(tweet) {
        var src = tweet.getAttribute("src");
        tweet.setAttribute("src", src.replace("theme=" + currentTheme, "theme=" + targetTheme));
    });
}

Try it out by switching theme on the top right ☝