gpt4 book ai didi

javascript - js中src属性的getter/setter?

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:57 26 4
gpt4 key购买 nike

有什么方法可以设置所有 HTMLSourceElements 的 src 属性的 getter 和 setter?我正在考虑将此用作我的网络应用程序的额外安全措施,该应用程序使用其他网站的 JS。通过“所有 HTMLSourceElements 的 src 属性的 setter ”,我的意思是应该在代码上调用 setter ,例如: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)

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)

有什么办法吗?或者这根本不可能?谢谢:)

最佳答案

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

编辑:经过一些实验后,如果您随后删除 您需要的每个元素的src 属性,这应该会起作用。有点老套,但我已经尽力了。

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

关于javascript - js中src属性的getter/setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22302940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com