DeveloperBreeze

Background Script Development Tutorials, Guides & Insights

Unlock 1+ expert-curated background script tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your background script skills on DeveloperBreeze.

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

Tutorial December 10, 2024
javascript css html

console.log("[content.js] Script loaded and running...");

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.action === "postTweet") {
    try {
      const tweetBox = document.querySelector('div[data-testid="tweetTextarea_0"]');
      if (!tweetBox) throw new Error("Tweet input field not found.");

      tweetBox.focus();
      document.execCommand("insertText", false, request.tweet);

      const tweetButton = document.evaluate(
        '//*[@data-testid="tweetButton"]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      ).singleNodeValue;

      if (!tweetButton) throw new Error("Tweet button not found.");
      tweetButton.click();

      sendResponse({ success: true });
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }
});

The popup.html file provides a simple UI for users to control the extension. Add this HTML code: