@CCO

Tampermonkey Замена кода script.js при загрузке страницы?

Прошу помочь написать Tampermonkey скрипт для перевода сайта https://www.figma.com/ (хороший бесплатный онлайн конструктор интерфейсов) на мой родной язык.

Сайт подгружает https://www.figma.com/figbuild-artifacts/figma_app..., в котором есть блок со словарём на энглише, который нужно подменить на мой собственный переведеный.
spoiler
(function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultStringsRaw={"abandon-reattach":"Abandon and reattach multiplayer","after-selecting-points":"After selecting points…","align-bottom":"Align bottom","align-centers":"Align centers","align-horizontal-center":"Align horizontal centers","align-left":"Align left","align-right":"Align right","align-left-right":"Align left/right","align-top":"Align top","align-top-bottom":"Align top/bottom","align-vertical-center":"Align vertical centers","arrange-menu":"Arrange","back-to-files":"Back to files","bend-tool":"Bend tool",bevel:"Bevel","boolean-menu":"Boolean groups","bring-forward":"Bring forward","bring-to-front":"Bring to front","center-resize-drag":"Resize from center","clear-empty-prototype-interactions":"Clear empty prototype interactions","command-bar-mode-all":"all","command-bar-mode-all-label":"Quick command","command-bar-mode-all-hint":"Type anything (action, layer, file, etc.)","command-bar-mode-run":"run","command-bar-mode-run-label":"Run","command-bar-mode-run-hint":"Run a menu action","command-bar-mode-goto":"goto","command-bar-mode-goto-label":"Goto layer","command-bar-mode-goto-hint":"Goto a layer","command-bar-mode-insert":"insert","command-bar-mode-insert-label":"Insert component","command-bar-mode-insert-hint":"Insert a component","command-bar-mode-open":"open","command-bar-mode-open-label":"Open file","command-bar-mode-open-hint":"Open a file","convert-to-raster":"Rasterize selection","copy-as-menu":"Copy as","copy-paste-menu":"Copy/Paste","copy-as-css":"Copy as CSS","copy-as-svg":"Copy as SVG","copy-as-png":"Copy as PNG","copy-properties":"Copy properties","copy-text":"Copy as text",copy:"Copy","create-symbol":"Create component","create-multiple-symbols":"Create multiple components","create-state":"Create variant","create-text-style":"Create text style","create-paint-style":"Create color style","create-effect-style":"Create effect style","create-stroke-style":"Create stroke style","crop-image":"Crop image",cut:"Cut","debug-menu":"Debug","debug-selection":"Debug log selection","deep-select":"Deep select","deep-select-rectangle":"Deep select within rectangle","deep-pick":"Select layer menu","delete-and-heal-selection":"Delete and heal selection","delete-selection":"Delete","deselect-all":"Select none","detach-all-instances":"Deep detach all selected instances","detach-instance":"Detach instance","detach-multiplayer":"Detach multiplayer","discard-all-images":"Discard all","distribute-bottom":"Distribute bottom","distribute-horizontal-center":"Distribute horizontal centers","distribute-horizontal-spacing":"Distribute horizontal spacing","distribute-left":"Distribute left","distribute-right":"Distribute right","distribute-top":"Distribute top","distribute-spacing":"Distribute spacing","distribute-vertical-center":"Distribute vertical centers","distribute-vertical-spacing":"Distribute vertical spacing","download-webgl-trace":"Download WebGL trace","duplicate-in-place":"Duplicate",duplicate:"Duplicate selection","edit-menu":"Edit","edit-shape-or-image":"Edit shape or image","enter-feedback-mode":"Feedback","enter-layout-mode":"Edit","export-all-frames-to-pdf":"Export frames to PDF…","export-for-framer":"Export for Framer","export-selected-exportables":"Export…","export-selected-exportables-desc":"Export","figma-account-menu":"Help and account","file-menu":"File","find-symbol":"Go to main component","flatten-selection":"Flatten selection","flatten-selection-context-menu":"Flatten","flip-horizontal":"Flip horizontal","flip-vertical":"Flip vertical","frame-selection":"Frame selection","get-desktop-app":"Get desktop app","group-selection":"Group selection","hide-selected-nodes":"Hide selection","hide-sibling-layers":"Hide other layers","ignore-constraints":"Ignore constraints","ignore-constraints-desc":"Ignore constraints (frames only)","collapse-layers":"Collapse layers","new-from-sketch":"New from Sketch file…","insert-component-right-text":"from #{name}","integrations-menu":"Integrations","community-hub-menu":"Community hub","plugins-menu":"Plugins","plugins-menu-manage":"Manage plugins…","plugins-menu-dev":"Development","plugins-menu-item":"#{plugin_name}","plugins-menu-sub-item":"#{plugin_sub_name}","plugins-menu-item-run":"Run…","plugins-menu-item-share":"Share…","plugins-menu-show-deprecated":"Deprecated plugins…","plugins-menu-internal-dev-modal":"Internal dev…","plugins-menu-use-desktop":"Not available","plugins-menu-dev-create-new":"New plugin…","plugins-menu-dev-add":"Add plugin from file…","plugins-menu-dev-toggle-realms":"Use developer VM","plugins-menu-add-from-key":"Add plugin from key…","plugins-menu-item-reload":"Reload","plugins-menu-item-remove":"Remove…","plugins-menu-open-directory-mac":"Reveal in Finder","plugins-menu-open-directory-win":"Reveal in Explorer","plugins-menu-open-console":"Open console","plugins-menu-show-error":"Show error details…","plugins-menu-plugin-missing":"⚠ Plugin missing","plugins-menu-manifest-issue":"⚠ Manifest issue","plugins-run-last":"Run last plugin","plugins-realms-vm":"Developer VM","join-selection":"Join selection","labeled-menu-item":"#{label}","leave-edit-mode":"Done","leave-history-edit-mode":"Exit version history mode","leave-vector-edit-mode":"Exit vector edit mode (Esc)","line-height-update-info":"The new rendering changes the line height behavior and fixes many bugs. You can always undo the update.","link-copied":"Link copied to clipboard","live-boolean-intersect":"Intersect selection","live-boolean-subtract":"Subtract selection","live-boolean-union":"Union selection","live-boolean-xor":"Exclude selection","lock-selected-nodes":"Lock selection","mask-selection":"Use as mask","unmask-selection":"Remove mask","main-component":"Main component","measure-to-selection":"Measure to selection",miter:"Miter","mobile-app-push":"View on mobile","move-while-resizing":"Move while resizing","navigation-navigate":"Navigate","navigation-overlay":"Open overlay","navigation-"},t.defaultStrings=t.defaultStringsRaw})

Пробовал просто полностью заменить figma_app.029257067ade81c2e77dc715510aea42.min.js.br на свой собственный , не сработало страница тупо непрогружается(((

В джава я тупой, нагуглил скрипт подмены кода до загрузки срницы, но он увы не работает.
// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *://*www.figma.com/*
// @include      *://*www.figma.com/*
// @require      http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @grant        none
// @run-at       document-start
// ==/UserScript==

window.addEventListener('beforescriptexecute', function(e) {
    src = e.target.src;
    content = e.target.text;
    console.log("src: " + src);
    if (src.search("figma_app.029257067ade81c2e77dc715510aea42.min.js.br") > -1) {
        var newContent = "";
        $.ajax({
            async: false,
            type: 'GET',
            url: '/figma_app.029257067ade81c2e77dc715510aea42.min.js.br',
            success: function(data) { //inject code via search and replace
                newContent = data.replace('Copy as CSS', 'Копировать CSS');
            }
        });
        // Stop original script
        e.preventDefault();
        e.stopPropagation();
        window.jQuery(e.target).remove();
        var script = document.createElement('script');
        script.textContent = newContent;
        (document.head || document.documentElement).appendChild(script);
        script.onload = function() {
            this.parentNode.removeChild(this);
            }
        });
    }
});
  • Вопрос задан
  • 1735 просмотров
Решения вопроса 1
Aetae
@Aetae Куратор тега JavaScript
Тлен
В данном случае можно воспользоваться старым трюком с геттером на свойство, т.к. оно имеет достаточно уникальное имя, и не извращаться(больше чем следует):
// ==UserScript==
// @name         figma.com translate
// @namespace    figma.com
// @version      0.1
// @author       Aetae
// @match        *://*.figma.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

Object.defineProperty(Object.prototype, 'defaultStringsRaw', {
  set(defaultStringsRaw) {
    delete Object.prototype.defaultStringsRaw;
    this.defaultStringsRaw = Object.assign(defaultStringsRaw, {
      "copy-as-css": "Копировать CSS",
    });
  },
  configurable: true
});
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега JavaScript
Если предположить, что нагугленный вами скрипт верен, то код должен выглядеть так:
window.addEventListener('beforescriptexecute', function(e) {
    if (e.target.src.search("figma_app.029257067ade81c2e77dc715510aea42.min.js.br") > -1) {
        // Stop original script
        e.preventDefault();
        e.stopPropagation();
        e.target.remove();

        fetch(e.target.src)
          .then(function (response) {
            return response.text();
          })
          .then(function (content) {
            return content.replace('Copy as CSS', 'Копировать CSS');
          })
          .then(function (newContent) {
            var script = document.createElement('script');
            script.textContent = newContent;
            (document.head || document.documentElement).appendChild(script);
            script.onload = function() {
              this.parentNode.removeChild(this);
            }
          });
    }
});


Но 029257067ade81c2e77dc715510aea42 - это хэш содержимого файла и при каждом изменении исходника адрес будет меняться, а ваш скрипт переставать работать.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
22 нояб. 2024, в 08:04
1 руб./за проект
22 нояб. 2024, в 06:06
1500 руб./в час
22 нояб. 2024, в 06:04
1 руб./за проект