Turbowarp for Scratch

Converts the project page & editor to Turbowarp versions.

2023-06-27 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

// ==UserScript==
// @name         Turbowarp for Scratch
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Converts the project page & editor to Turbowarp versions.
// @author       You
// @match        https://scratch.mit.edu/projects/*
// @match        https://turbowarp.org/*
// @icon         https://turbowarp.org/images/192.png
// @license      MIT
// @grant        none
// ==/UserScript==

if (document.location.href.includes('turbowarp') && document.referrer == 'https://scratch.mit.edu/') {
    console.log('Came from Turbowarp for Scratch');
} else {
setInterval(function() {
  if (document.location.href == 'https://scratch.mit.edu/projects/editor/') {
      window.onbeforeunload = null;
      document.location.href = 'https://turbowarp.org/editor';
  } else {
    if (document.location.href.includes('editor') && document.location.href != 'https://scratch.mit.edu/projects/editor/') {
      function extractProjectId(url) {
        url = url.replace(/\/+$/, '');

        var segments = url.split('/');
        var projectId = segments[segments.length - 2];

        return projectId;
      }

      var projectId = extractProjectId(document.location.href);
        const state = { page_id: 1, user_id: 5 };
        const url = document.location.href.replace(/(https:\/\/scratch\.mit\.edu\/projects\/\d+\/).*/, "$1");
        history.pushState(state, "", url);
        window.onbeforeunload = null;
        document.location.href = `https://turbowarp.org/${projectId}/editor`;
    }
  }
}, 100);

const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
      const targetElement = document.querySelector("#view > div > div.inner > div:nth-child(2) > div.guiPlayer");

      if (targetElement) {
        function extractProjectId(url) {
          url = url.replace(/\/+$/, '');
          var segments = url.split('/');
          var projectId = segments[segments.length - 1];

          return projectId;
        }

        var projectId = extractProjectId(document.location.href);

        document.querySelector("#view > div > div.inner > div:nth-child(2) > div.guiPlayer").innerHTML = `<iframe src="https://turbowarp.org/${projectId}/embed?addons=pause&settings-button" width="490" height="414" allowtransparency="true" frameborder="0" scrolling="no" allowfullscreen></iframe>`

        observer.disconnect();
      }
    }
  }
});

observer.observe(document.body, { childList: true, subtree: true });
}