Hemanth's Scribes

javascript

Redefining DOM Object's Behaviour

Author Photo

Hemanth HM

Thumbnail

Object.defineProperty is useful for defining or modifying properties. But I faced an interesting scenario redefining a video element’s src attribute.

The Naive Approach (Causes Recursion)

var video = document.createElement('video');
var videos = { comedy: '', drama: '' };

Object.defineProperty(video, 'src', {
  set: function(type) {
    this.src = videos[type];  // Infinite recursion!
  }
});

This causes InternalError: too much recursion (FF) or RangeError: Maximum call stack size exceeded (Chrome).

The Solution: Use setAttribute

Since video is a DOM node with IDL attributes, we can use setAttribute:

Object.defineProperty(video, 'src', {
  set: function(url) {
    this.setAttribute('src', videos[index]);
  }
});

video.src = comedy; // Now works as expected!

The trick is that setAttribute bypasses the property we just defined!

#javascript#dom
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.