Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!