Javascript js中src属性的getter/setter?
是否有任何方法可以设置所有HTMLSourceElements的src属性的getter和setter? 我正在考虑使用它作为我的web应用程序的额外安全措施,它使用来自其他网站的JS。 所谓“所有HTMLSourceElements的src属性的setter”,我的意思是应该在如下代码上调用setter: SomeVideoElement.src=“/static/somevideo.mp4” 到目前为止,我已经尝试:Javascript js中src属性的getter/setter?,javascript,html,Javascript,Html,是否有任何方法可以设置所有HTMLSourceElements的src属性的getter和setter? 我正在考虑使用它作为我的web应用程序的额外安全措施,它使用来自其他网站的JS。 所谓“所有HTMLSourceElements的src属性的setter”,我的意思是应该在如下代码上调用setter: SomeVideoElement.src=“/static/somevideo.mp4” 到目前为止,我已经尝试: HTMLElement.prototype.__defineGetter_
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)
及
有没有办法做到这一点?还是这根本不可能?
谢谢:)var srcmelements=document.querySelectorAll(“[src]”);
对于(var i=0;i\uuuuuuuuuuuuuuuuuuuuuuu
和\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
已弃用,可能已过时<代码>对象。定义属性(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
您需要删除的每个元素的src>属性,这应该可以工作。有点老套,但我已经尽力了
EDIT2:这样,用户理论上仍然可以覆盖get/set函数。要停止此操作,请尝试删除可配置:true
(默认为false)。我不确定,但根据过去的经验,似乎他们甚至不能在实例上重新定义它。你应该玩一下。例如,您可以通过以下方式查看图像属性的更改:
var target = document.querySelector('#image');
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
alert('Change: ' + mutation.attributeName + ', ' + mutation.oldValue);
});
});
observer.observe(target, {
attributes: true,
attributeOldValue: true
});
支持:所有现代浏览器和IE11+
演示:\uuuuuuuuuuuuuuuuuuuuuuuuuuuu
和\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。不要在面向Web的生产站点上使用它:它不会对每个用户都有效。只是说,这里的一些答案似乎并不理解这个问题。无论您采取了什么安全措施,您仍然无法信任外部代码。仍然只需简单的编辑即可使setter/getter逻辑无效。这适用于使用document.createElement
创建的元素定义属性后,我尝试了很多实验。。。但是JS似乎不能做我想让它做的事。。。但是这个答案与我想做的最接近(比如JS中的预处理?——所以我接受你的:)在大多数浏览器上,你不需要从对象中删除属性,它只在原型级别上工作。在Chrome上,你需要删除object.src
,才能让这个技巧发挥作用。谢谢。我认为您的也有点接近,但它只在DOM元素之后加载“var target=document.querySelector(“#image”);”时才起作用……但无论如何,这是您的+1,因为它已经接近了:)
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);
}
});
var target = document.querySelector('#image');
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
alert('Change: ' + mutation.attributeName + ', ' + mutation.oldValue);
});
});
observer.observe(target, {
attributes: true,
attributeOldValue: true
});