js中src属性的getter / setter?

时间:2014-03-10 14:28:39

标签: javascript html5

有什么办法可以设置所有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)

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

3 个答案:

答案 0 :(得分:4)

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

编辑:经过一些实验,如果您delete所需的每个元素的src属性,这应该有用。有点hacky,但我能做的最好。

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

答案 1 :(得分:2)

你应该玩MutationObserver。例如,您可以观看图像属性更改:

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 +。

演示:http://jsfiddle.net/dfsq/PmTHj/1/

答案 2 :(得分:0)

var srcElements = document.querySelectorAll('[src]');
for(var i = 0; i < srcElements.length; i++){
    if( typeof(srcElements[i].src) != 'undefined' ){
        console.log(srcElements[i] + ' has a src property');
    }    
}
相关问题