Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda