js中src属性的getter / setter? [英] getter/setter for src attribute in js?

查看:112
本文介绍了js中src属性的getter / setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Are there any way I can set getters and setters of src attribute of all HTMLSourceElements? I'm thinking about using this as an extra security measures for my web app which uses JS from other websites. By "setters of src attribute of all HTMLSourceElements", I mean that the setter should be called on code like: SomeVideoElement.src = "/static/somevideo.mp4"

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

So far, I've tried:

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)

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)

有没有办法做这个?或者这根本不可能?
谢谢:)

are there any way to do this? Or is this simply impossible? Thanks : )

推荐答案

__ defineGetter __ __ defineSetter __ 已弃用且可能已过时。 Object.defineProperty(parentObject,'propName',{})是新方式。

__defineGetter__ and __defineSetter__ are deprecated and possibly obsolete. Object.defineProperty(parentObject, 'propName', {}) is the new way.

我不能让它工作,但也许其他人可以吗?

I couldn't get it to work, but maybe someone else can?

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);
    }
});

编辑:经过一些实验,如果你那么删除这应该有效您需要的每个元素的 src 属性。有点hacky,但我能做的最好。

After a bit of experimentation, this should work if you then delete the src property of every element that you need to. A bit hacky, but the best i could do.

EDIT2:有了这个,理论上用户仍然可以覆盖你的get / set函数。要停止它,请尝试删除 configurable:true (它将默认为false)。我不确定,但从过去的经验来看,似乎他们甚至无法在一个实例上重新定义它。

With this, a user could still theoretically overwrite your get/set functions. To stop that, try removing configurable: true (it will default to false). I'm not sure, but from past experience, it seems like they can't even redefine it on an instance.

这篇关于js中src属性的getter / setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆