Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Redefining DOM Object's Behaviour

| Comments

Object.defineProperty has been very useful for defining new properties or modifying the existing ones.

But faced an intresting senario of redefining video element's src attribute.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Let's create a video element.
var video = document.createElement('video');
var videos = {
    comedy: '',
    drama: ''
}; //Some collection.

// Let's try to redefine the src attr.
Object.defineProperty(video, 'src', {
    set: function (type) {
        this.src = videos[type];
    }
});

video.src = comdey; // This must set src to comedy video.

But for much obvio recursion we get InternalError: too much recursion on FF and RangeError: Maximum call stack size exceeded on Chrome.

As I was looking for a backdoor, one my colleagues @sashvini suggested a trick using setAttribute as video element was a DOM node with IDL attributes and methods are exposed to dynamic scripts.

Vola! It worked.

1
2
3
4
5
6
7
Object.defineProperty(video, 'src', {
    set: function (url) {
        this.setAttribute('src', videos[index]);
    }
});

video.src = comedy; // Now works as expected :)

P.S : The real use case for this was more complicated, have taken a silly example just to prove this!

Hope this is useful and there maybe many other ways to do this, do tell me know if you are aware of one such! (:

Comments