Home > OS >  Overriding HTML img src assignments
Overriding HTML img src assignments

Time:05-19

I am trying to dynamically override all IMG url assigments by redefining property of Image/HTMLImage object. It correctly intercepts assignments, but new URLs don't work and it appears it screws ability of img to work normally work at all.

Is this possible to do with something other that defineProperty (e.g. mutation observer)?

(p.p.s. for my certain use case, assigning this.srcset=e; works well but it's ugly)

<html>
<body>
<script>
if(!window.once) {
window.once = 1;

Object.defineProperty( 
    Image.prototype,'src',{configurable: true
    , get: function() { 
      console.log(this.__src);
    return this.__src; }

    , set: function(e) {
        if(e.includes('replacemask')) {
         e='rep.jpg';
    }
    this.__src=e; console.info('aaa:', e) } });

}       

var x = new Image;
x.src="-.jpg";

document.body.append(x);

</script>
</body>
</html>     

CodePudding user response:

You need to first extract the "original" setter and getters and call these in your own:

// get the original descriptor
const desc = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src");
Object.defineProperty(
  HTMLImageElement.prototype, "src", {
    ...desc,
    get: function() {
      console.log(this.__src);
      // call the original getter
      return desc.get.call(this);
    },
    set: function(e) {
      if (e.includes('replacemask')) {
        e = e.replace('replacemask', 'demonstration_1.png');
      }
      // get the original setter
      desc.set.call(this, e);
      console.info('aaa:', e)
    }
  });

var x = new Image;
x.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_replacemask";
document.body.append(x);

However beware this isn't the only way to update an HTMLImageElement's current source. You have the obvious setAttribute, but also the less obvious srcset and <picture><source> cases.

  • Related