Bernhard Bernhard - 1 year ago 159
HTML Question

greasemonkey help (replace html tags)

I am new to greasemonkey and would like to learn to use it to remove javascript enforcers. Like this one

<span class="lazyload" style="display:block; width:100%;height:100%;" data-imgSrc="//" data-imgAlt="nevermind"></span>

that should read

<img style="width:100%; height:100%;" src="" data-imgAlt="nevermind">

In principle this can be done by some search&replaces. In sed-speak

's|span class="lazyload" style="display:block;|img style="|gi'

does the job.

As pointed out a lot, (here for example RegEx match open tags except XHTML self-contained tags),
such replacements may be bad. But when applied to a specific page they are quick ...

thank you!

Answer Source

Forget about regexps when dealing with live web pages because replacing HTML directly will break event listeners (click handlers etc.) attached in js code via addEventListener or .on properties.

Here's an excerpt from the code I'm using.


// also delazify new dynamically added content
new MutationObserver(delazify).observe(document, {subtree: true, childList: true});

function delazify() {
    var lazies = document.getElementsByClassName('lazyload');
    for (var i = lazies.length; --i >= 0; ) {
        var el = lazies[i];
        var src = el.getAttribute('data-imgSrc');
        if (src) {
            el.src = src;

It's really simple, the only noteworthy thing is that in MutationObserver callback instead of looping through mutation records and added nodes, which may be slow in case of lots of nodes, I directly iterate by class name because getElementsByClassName is extremely fast.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download