Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
Overriding HTML img src assignments

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>     

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda