Discussões » Criação de Solicitações
Replace text with random characters or digits
Here's a low-latency code that doesn't make pages load slower and works on dynamically added content too.
// ==UserScript==
// @name Random elephant
// @include *
// @grant none
// @run-at document-start
// ==/UserScript==
// if Chrome was too fast and has prerendered the document
if (document.body && document.body.textContent.toLowerCase().indexOf('elephant') > 0) {
randomizeElephant('childNodes', document.body.getElementsByTagName("*"));
}
// watch the page as it's being loaded and randomize the elephants
new MutationObserver(randomizeElephant.bind(undefined, 'addedNodes'))
.observe(document, {subtree:true, childList:true});
// process the array of nodes/mutations
function randomizeElephant(place, array) {
for (var i=0, al=array.length, a; (i<al) && (a=array[i]); i++) {
for (var j=0, nodes=a[place], nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++) {
if (n.nodeType == Node.TEXT_NODE) {
var s = n.textContent.replace(/elephant/gi, function(text) {
return Math.random().toString(36).substr(3,13);
});
if (s != n.textContent) {
n.textContent = s;
}
}
}
}
}
Replace // @include *
with // @include http://some.site/*
if you want to restrict it to a specific site.
Thank you very much. This works, but I need the script to alter text in the source element and not just what is processed on the screen--if that makes sense.
* It is probably not as simple as I made it sound--the text elephant would be part of a URL inside the page, and it is that text that I would like to be randomized if this is possible. I have managed to replace the text, but I cannot seem to figure out how to combine this with randomization.
alter text in the source element and not just what is processed on the screen--if that makes sense.
Example?
I cannot seem to figure out how to combine this with randomization.
Use a function for replacement:
.replace(/elephant/gi, function(text) {
return Math.random().toString(36).substr(3,13);
});
An example would be an iframe URL of http://www.google.com/test?animal=elephant in which the 'elephant' portion was randomized.
I just tried your replace function and it works perfectly with the innerhtml code I was using. Thank you so much.
Ah, I doubted innerHTML would work without glitches, thus resorted to node enumeration.
Replace text with random characters or digits
I am quite the beginner with javascript and have failed at my attempts to do this on my own. I would like to replace specific text (for example, the word elephant) with a random series of 13 letters or digits.