Discussions » Development

Modifying JavaScript Content on Website Using Tampermonkey

§
Posted: 2023-12-14

Hi everyone,

I'm new to using Tampermonkey and I need some guidance. I want to modify the content of a JavaScript file on website using Tampermonkey, and I'm looking for assistance in creating the script.

The thing is that for the script I want to work, it needs certain information, and this information is not displayed on the website and is not saved in any variable. I want to add code to a loop that knows this value, that will store this value in a hidden form so that the script can use it

Can someone provide guidance or an example script for this?

Thanks in advance for your help!

§
Posted: 2023-12-14
Edited: 2023-12-14

This is a complicated topic but that pixlr script is using one of the methods you're looking for. It might not suit your needs though... Would it take a long time for you to message here what website and what page and what js file and what function and what value you want to intercept? This will make things easier

§
Posted: 2023-12-15

First of all you will know about the help.
Sorry if I'm not clear, English is difficult for me and I use google translate

I want to write scripts to improve the quality of life in the game Heart of Galaxy Horizons at https://game288398.konggames.com/gamez/0028/8398/live/game.html

Specifically, the change I want to make is to add at the end of this loop in the code-

if("auto"==fleetSchedule.fleets[e[d].fleet].type){for(var u=fleetSchedule.fleets[e[d].fleet],v=e[d].origin,J=e[d].destination,D=parseInt(Math.floor(2*planets[v].shortestPath[J].distance/(u.speed()*idleBon))),y=0,x=0,va=0;va<
resNum;va++)u.autoPct[va]?0>planets[v].globalRaw[va]?x+=-u.autoRes[u.autoMap[v]][va]/1E4*planets[v].globalRaw[va]*D:y+=u.autoRes[u.autoMap[v]][va]/1E4*planets[v].globalRaw[va]*D:y+=u.autoRes[u.autoMap[v]][va],u.autoPct[va]?0>planets[J].globalRaw[va]?y+=-u.autoRes[u.autoMap[J]][va]/1E4*planets[J].globalRaw[va]*D:x+=u.autoRes[u.autoMap[J]][va]/1E4*planets[J].globalRaw[va]*D:x+=u.autoRes[u.autoMap[J]][va];y=Math.floor(y);x=Math.floor(x);y>u.maxStorage()&&(n=!0,l+=" (Not enough storage in "+
planets[v].name);x>u.maxStorage()&&(l=n?l+(" and "+planets[J].name):l+(" (Not enough storage in "+planets[J].name),n=!0);n&&(l+=") ")}

this code-

var MoreStorageNeed = Math.max(x, y) - u.maxStorage();
if (MoreStorageNeed > 0) {
var hiddenElement = document.createElement("div");
hiddenElement.style.display = "none";
hiddenElement.innerHTML = "Additional Storage Needed: " + MoreStorageNeed;
l += hiddenElement.outerHTML;
}

§
Posted: 2023-12-15

Lucky the method from the pixlr script seems to be working, though I can't approve since I'm not playing the game and have no idea what's going on. Also the first code you've mentioned is differs from the current game code, but I think I've did everything right...

// ==UserScript==
// @name          Inject attempt
// @description   Inject attempt
// @version       1
// @match         https://game288398.konggames.com/gamez/0028/8398/live/game.html
// @icon          https://game288398.konggames.com/favicon.ico
// @run-at        document-start
// ==/UserScript==

// STRING_TO_INJECT would be inserted right after where the TARGET_STRING ends

(() => {
  'use strict';

  const TARGET_STRING =
    `x>u.maxStorage()&&(l=n?l+(" and "+planets[J].name):l+("<span class='red_text' style='font-size:70%;'> (Not enough storage in "+planets[J].name),n=!0);n&&(l+=") </span>")`;

  /* eslint-disable no-undef */
  const STRING_TO_INJECT = '(' + (function() {
    var MoreStorageNeed = Math.max(x, y) - u.maxStorage();

    if (MoreStorageNeed > 0) {
      var hiddenElement = document.createElement('div');

      hiddenElement.innerHTML = 'Additional Storage Needed: ' + MoreStorageNeed;
      hiddenElement.style.display = 'none';

      l += hiddenElement.outerHTML;
    }
  }).toString() + '());';
  /* eslint-enable no-undef */

  async function patchScript(node) {
    node.remove();

    let scriptCode = await (await fetch(node.src)).text();

    const newNode = document.createElement('script');
    const targetIndex = scriptCode.indexOf(TARGET_STRING);

    if (targetIndex === -1) {
      alert('Failed to inject! The game probably was updated');
    } else {
      scriptCode =
        scriptCode.substring(0, targetIndex + TARGET_STRING.length) +
        STRING_TO_INJECT +
        scriptCode.substring(targetIndex + TARGET_STRING.length);
    }

    newNode.innerHTML = scriptCode;

    document.body.appendChild(newNode);
  }

  new MutationObserver((mutationsList, obs) => {
    mutationsList.forEach((mutationRecord) => {
      for (const node of mutationRecord.addedNodes) {
        if (node.src?.endsWith('/core/script/sall.js')) {
          obs.disconnect();
          patchScript(node);
        }
      }
    });
  }).observe(document, { childList: true, subtree: true });
})();
§
Posted: 2023-12-15

If this alerts with Failed to inject, change the TARGET_STRING to x>u.maxStorage()&&(l=n?l+(" and "+planets[J].name):l+(" (Not enough storage in "+planets[J].name),n=!0);n&&(l+=") ")

§
Posted: 2023-12-15

A bit better:

// ==UserScript==
// @name          Inject attempt
// @description   Inject attempt
// @version       2
// @match         https://game288398.konggames.com/gamez/0028/8398/live/game.html
// @icon          https://game288398.konggames.com/favicon.ico
// @run-at        document-start
// ==/UserScript==

// STRING_TO_INJECT would be inserted right after where the TARGET_STRING ends

(() => {
  'use strict';

  const TARGET_STRING =
    `x>u.maxStorage()&&(l=n?l+(" and "+planets[J].name):l+("<span class='red_text' style='font-size:70%;'> (Not enough storage in "+planets[J].name),n=!0);n&&(l+=") </span>")`;

  /* eslint-disable no-undef */
  const STRING_TO_INJECT = '(' + (function() {
    try {
      var MoreStorageNeed = Math.max(x, y) - u.maxStorage();

      if (MoreStorageNeed > 0) {
        var hiddenElement = document.createElement('div');

        hiddenElement.innerHTML = 'Additional Storage Needed: ' + MoreStorageNeed;
        hiddenElement.style.display = 'none';

        l += hiddenElement.outerHTML;
      }
    } catch (e) {
      console.error('Injection script error:');
      console.error(e);
    }
  }).toString() + '());';
  /* eslint-enable no-undef */

  async function patchScript(node) {
    node.remove();

    let scriptCode = await (await fetch(node.src)).text();

    const newNode = document.createElement('script');
    const targetIndex = scriptCode.indexOf(TARGET_STRING);

    if (targetIndex === -1) {
      alert('Failed to inject! The game probably was updated');
    } else {
      scriptCode =
        scriptCode.substring(0, targetIndex + TARGET_STRING.length) +
        STRING_TO_INJECT +
        scriptCode.substring(targetIndex + TARGET_STRING.length);
    }

    newNode.innerHTML = scriptCode;

    document.body.appendChild(newNode);
  }

  new MutationObserver((mutationsList, obs) => {
    mutationsList.forEach((mutationRecord) => {
      for (const node of mutationRecord.addedNodes) {
        if (node.src?.endsWith('/core/script/sall.js')) {
          obs.disconnect();
          patchScript(node);
          break;
        }
      }
    });
  }).observe(document, { childList: true, subtree: true });
})();
§
Posted: 2023-12-17

thank you very much for the help! You advanced me in what I couldn't advance alone in the end.
I will share with you the code that finally works for me. Of course, this is only the first part of a more significant operation, but it was a serious obstacle on my way to the code I wanted...
Sorry if what I say is not clear, I use Google Translate

// ==UserScript==
// @name Inject attempt
// @description Inject attempt
// @version 3
// @match *://game288398.konggames.com/gamez/0028/8398/live/*
// @icon http://game288398.konggames.com/favicon.ico
// @run-at document-start
// ==/UserScript==

// STRING_TO_INJECT would be inserted right after where the TARGET_STRING ends

(() => {
'use strict';

const TARGET_STRING =
`x>u.maxStorage()&&(l=n?l+(" and "+planets[J].name):l+(" (Not enough storage in "+planets[J].name),n=!0);n&&(l+=") ")`;

/* eslint-disable no-undef */
const STRING_TO_INJECT = `
var MoreStorageNeed = Math.max(x, y) - u.maxStorage();
console.log(MoreStorageNeed);
if (MoreStorageNeed > 0) {
l += ' ' + 'Additional Storage Needed: ' + MoreStorageNeed + '';
}
`;
/* eslint-enable no-undef */

async function patchScript(node) {
node.remove();

let scriptCode = await (await fetch(node.src)).text();

const newNode = document.createElement('script');
const targetIndex = scriptCode.indexOf(TARGET_STRING);

if (targetIndex === -1) {
alert('Failed to inject! The game probably was updated');
} else {
scriptCode =
scriptCode.substring(0, targetIndex + TARGET_STRING.length) +
STRING_TO_INJECT +
scriptCode.substring(targetIndex + TARGET_STRING.length);
}

newNode.innerHTML = scriptCode;

document.body.appendChild(newNode);
}

new MutationObserver((mutationsList, obs) => {
mutationsList.forEach((mutationRecord) => {
for (const node of mutationRecord.addedNodes) {
if (node.src?.endsWith('/core/script/sall.js')) {
obs.disconnect();
patchScript(node);
break;
}
}
});
}).observe(document, { childList: true, subtree: true });
})();

§
Posted: 2024-01-30

MutationObserver + Regex.

Post reply

Sign in to post a reply.