In this tutorial, we will walk you through building a fully functional Chrome extension that automates tweets on X (formerly Twitter). This extension allows you to create tweets from a pre-defined list and post them automatically on your X account at regular intervals.

We'll break the tutorial into clear, manageable steps so even if you're a beginner, you can follow along.


Step 1: Setting Up the Project

Before diving into the code, let's set up the structure for our Chrome extension. You'll need:

  1. A code editor (like Visual Studio Code).
  2. Google Chrome installed on your computer.
  3. Basic knowledge of JavaScript.

Create the Project Files

Create a new folder for your project, and within it, create the following files:


- manifest.json
- background.js
- content.js
- popup.html
- popup.js

Each file has a specific role:

  • manifest.json: Defines the extension's metadata and permissions.
  • background.js: Runs in the background to handle tweet automation logic.
  • content.js: Interacts with the X website.
  • popup.html: The user interface for starting/stopping the automation.
  • popup.js: Handles user interactions from the popup.

Step 2: Writing the Manifest File

The manifest.json is the heart of the extension. It defines the extension's properties and permissions. Paste the following code into your manifest.json file:


{
  "manifest_version": 3,
  "name": "X.com Tweet Automation",
  "version": "1.0",
  "description": "Automate tweets on X.com.",
  "permissions": ["activeTab", "scripting"],
  "host_permissions": ["https://x.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["https://x.com/*"],
      "js": ["content.js"]
    }
  ]
}

Key Sections

  • manifest_version: Specifies the version of the manifest. Chrome requires version 3 for newer extensions.
  • permissions: Grants the extension access to scripting and the active tab.
  • host_permissions: Restricts the extension to only work on X.com.

Step 3: Building the Background Script

The background.js file contains the logic for automating tweets. Copy the following code into background.js:


let intervalId = null;
const tweets = ["https://developerbreeze.com/post/59"];
let engage = [
  "Want to code like a pro?  These tutorials will get you there in no time! ",
  "Struggling with coding?  These beginner-friendly tips will blow your mind! ",
];

let currentTweetIndex = 0;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "start") {
    if (!intervalId) {
      intervalId = setInterval(() => {
        const currentTweet = tweets[currentTweetIndex];
        const randomEngage = engage[Math.floor(Math.random() * engage.length)];
        const tweet = `${randomEngage} ${currentTweet}`;

        const encodedTweet = encodeURIComponent(tweet);
        const shareUrl = `https://x.com/intent/tweet?text=${encodedTweet}`;

        chrome.tabs.create({ url: shareUrl, active: true }, (tab) => {
          chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
            if (tabId === tab.id && info.status === "complete") {
              chrome.tabs.onUpdated.removeListener(listener);
              chrome.scripting.executeScript({
                target: { tabId },
                files: ["content.js"],
              });
            }
          });
        });

        currentTweetIndex = (currentTweetIndex + 1) % tweets.length;
      }, 300000); // Post every 5 minutes
      sendResponse({ status: "Running" });
    } else {
      sendResponse({ status: "Already Running" });
    }
  } else if (request.action === "stop") {
    clearInterval(intervalId);
    intervalId = null;
    sendResponse({ status: "Stopped" });
  }
});

Step 4: Writing the Content Script

The content.js file interacts directly with the X website to type and post tweets. Add the following code:


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 });
    }
  }
});

Step 5: Designing the Popup Interface

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




  Tweet Automation


  

Tweet Automation

Status: Idle


Step 6: Writing the Popup Script

The popup.js file links the buttons in the popup UI to the actions in the background script. Paste the following code into popup.js:


document.getElementById("start").addEventListener("click", () => {
  chrome.runtime.sendMessage({ action: "start" }, (response) => {
    if (chrome.runtime.lastError) {
      console.error("[popup.js] Error:", chrome.runtime.lastError.message);
      document.getElementById("status").innerText = "Error: Could not connect to background script.";
      return;
    }
    console.log("[popup.js] Response:", response);
    document.getElementById("status").innerText = `Status: ${response.status}`;
  });
});

document.getElementById("stop").addEventListener("click", () => {
  chrome.runtime.sendMessage({ action: "stop" }, (response) => {
    if (chrome.runtime.lastError) {
      console.error("[popup.js] Error:", chrome.runtime.lastError.message);
      document.getElementById("status").innerText = "Error: Could not connect to background script.";
      return;
    }
    console.log("[popup.js] Response:", response);
    document.getElementById("status").innerText = `Status: ${response.status}`;
  });
});

Step 7: Testing the Extension

Load the Extension in Chrome

  1. Open Google Chrome and navigate to chrome://extensions/.
  2. Enable Developer Mode (toggle at the top-right corner).
  3. Click Load Unpacked and select your project folder.

If everything is set up correctly, you should see your extension in the list with its name and icon.


Verify the Popup

  1. Click on the extension icon in the Chrome toolbar to open the popup.
  2. Check that the Start and Stop buttons appear and are clickable.
  3. The status message should update when you interact with the buttons.

Start Automation

  1. Press the Start button in the popup. The extension will begin posting tweets at intervals.
  2. Open X (Twitter) to confirm that the tweets are being posted correctly.
  3. You can click the Stop button to halt the automation.

Step 8: Fine-Tuning the Extension

Adjusting Intervals

In the background.js file, the interval for posting tweets is set to 5 minutes (300,000 milliseconds):


setInterval(() => {
  // Posting logic
}, 300000); // Adjust this value as needed

You can reduce or increase the frequency by changing this value.


Adding More Tweets and Messages

Expand the tweets and engage arrays in background.js to include more content:


const tweets = [
  "https://developerbreeze.com/post/59",
  "https://anotheramazingresource.com",
  "https://yetanothergreatsite.com",
];

const engage = [
  "Check this out! ",
  "Learn something new today! ",
  "This is a must-read! ",
];

Step 9: Deployment

Once you're satisfied with your extension, you can share it or publish it on the Chrome Web Store.

Pack the Extension

  1. Go to chrome://extensions/.
  2. Click Pack Extension.
  3. Select your project folder and follow the prompts to generate a .crx file.

Conclusion

Congratulations! You've built a fully functional Chrome extension for automating tweets on X. Along the way, you learned:

  • How to structure a Chrome extension project.
  • The roles of the manifest, background script, content script, and popup.
  • How to interact with web pages programmatically.

You can now modify and expand this extension to include features like scheduling specific tweets, logging analytics, or integrating with other social media platforms.