Skip to content

Instantly share code, notes, and snippets.

@yihui-hu
Created May 20, 2023 03:21
Show Gist options
  • Save yihui-hu/43b4c5c45cb2b32cfc7d653a64c5742d to your computer and use it in GitHub Desktop.
Save yihui-hu/43b4c5c45cb2b32cfc7d653a64c5742d to your computer and use it in GitHub Desktop.
ChatGPT helping me with getting the tweet ID from the injected XMLHttpRequest script

You cannot directly access the Chrome storage API from an injected script or communicate with the extension using message passing in this context.

In the injected script, you can, however, pass the tweetId value to the background script of your extension using a custom event and the dispatchEvent method. The background script can then handle storing the value in Chrome storage. Here's an updated version of your code:

Injected script (content script):

(function (xhr) {
  let XHR = XMLHttpRequest.prototype;

  let open = XHR.open;
  let send = XHR.send;
  let setRequestHeader = XHR.setRequestHeader;

  XHR.open = function (method, url) {
    this._method = method;
    this._url = url;
    this._requestHeaders = {};
    this._startTime = new Date().toISOString();

    return open.apply(this, arguments);
  };

  XHR.setRequestHeader = function (header, value) {
    this._requestHeaders[header] = value;
    return setRequestHeader.apply(this, arguments);
  };

  XHR.send = function (postData) {
    this.addEventListener("load", async function () {
      if (postData) {
        // Get request headers
        if (typeof postData === "string") {
          this._requestHeaders = postData;
        }
      }

      try {
        // Get request payload
        if (
          this._url.endsWith("FavoriteTweet") ||
          this._url.endsWith("CreateBookmark")
        ) {
          const requestPayload = JSON.parse(this._requestHeaders);
          const tweetId = requestPayload.variables.tweet_id;
          console.log(tweetId);

          // Dispatch custom event to the webpage
          const event = new CustomEvent("storeTweetId", {
            detail: { tweetId: tweetId },
          });
          document.dispatchEvent(event);
        }
      } catch (err) {
        console.error("Error parsing _requestHeaders.");
        console.error(err);
      }
    });

    return send.apply(this, arguments);
  };
})(XMLHttpRequest);

Background script:

// Listen for the custom event dispatched from the content script
document.addEventListener("storeTweetId", function (event) {
  const tweetId = event.detail.tweetId;
  console.log("Received tweetId:", tweetId);

  // Store the tweetId in Chrome storage
  chrome.storage.local.set({ tweetId: tweetId }, function () {
    if (chrome.runtime.lastError) {
      console.error("Error storing tweetId: " + chrome.runtime.lastError);
    } else {
      console.log("tweetId stored successfully");
    }
  });
});

With this approach, the injected script dispatches a custom event named "storeTweetId" to the webpage, passing the tweetId as part of the event's detail object. The background script listens for this custom event and retrieves the tweetId from the event to store it in Chrome storage using chrome.storage.local.set().

Remember to include the "storage" permission in your extension's manifest file (manifest.json) and ensure that the injected script (content script) and the background script are properly specified:

{
  "manifest_version": 2,
  "name": "Your Extension",
  "version": "1.0",
  "permissions": ["storage"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment