js中src属性的getter/setter?

Dev*_*ari 4 html javascript

有什么方法可以设置所有 HTMLSourceElements 的 src 属性的 getters 和 setters 吗?我正在考虑使用它作为我的网络应用程序的额外安全措施,该应用程序使用来自其他网站的 JS。通过“所有 HTMLSourceElements 的 src 属性的设置器”,我的意思是应该在以下代码上调用设置器:SomeVideoElement.src =“/static/somevideo.mp4”

到目前为止,我已经尝试过:

HTMLElement.prototype.__defineGetter__("src", function () {
    console.log("getter called!");
    debugger;
});
HTMLElement.prototype.__defineSetter__("src", function (val) {

    debugger;
});
//tested at chrome, didn't yield any logs (getters and setters not called)
Run Code Online (Sandbox Code Playgroud)

HTMLSourceElement.prototype._setAttribute = HTMLSourceElement.prototype.setAttribute;
HTMLSourceElement.prototype._getAttribute = HTMLSourceElement.prototype.getAttribute;
HTMLSourceElement.prototype.setAttribute = function(){
   console.log("HTMLSourceElement.setAttribute called!");
   debugger;
   HTMLSourceElement.prototype._setAttribute.apply(this, arguments);
}
//tested at chrome. Called only for codes like: SomeVidElem.setAttribute("src",someurl)
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点吗?或者这根本不可能?谢谢 : )

Sci*_*ter 5

__defineGetter__并且__defineSetter__已被弃用并且可能已过时。Object.defineProperty(parentObject, 'propName', {})是新的方式。

我无法让它工作,但也许其他人可以?

Object.defineProperty(HTMLSourceElement.prototype, 'src', {
    enumerable: true,
    configurable: true,
    get: function(){
        return this.getAttribute('src')
    },
    set: function(newval){
        console.log('being set');
        this.setAttribute('src',newval);
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:经过一些实验,如果您需要每个元素的属性,delete这应该可以工作。src有点老套,但我能做的最好的。

EDIT2:这样,理论上用户仍然可以覆盖您的获取/设置函数。要阻止这种情况,请尝试删除configurable: true(它将默认为 false)。我不确定,但从过去的经验来看,他们似乎甚至无法在实例上重新定义它。