簡體   English   中英

覆蓋 HTML img src 分配

[英]Overriding HTML img src assignments

我正在嘗試通過重新定義 Image/HTMLImage object 的屬性來動態覆蓋所有 IMG url 分配。它正確地攔截了分配,但是新的 URL 不起作用並且它似乎使 img 無法正常工作。

這可能與 defineProperty 的其他東西有關(例如突變觀察者)嗎?

(pps 對於我的某些用例,分配 this.srcset=e; 效果很好但很難看)

<html>
<body>
<script>
if(!window.once) {
window.once = 1;

Object.defineProperty( 
    Image.prototype,'src',{configurable: true
    , get: function() { 
      console.log(this.__src);
    return this.__src; }

    , set: function(e) {
        if(e.includes('replacemask')) {
         e='rep.jpg';
    }
    this.__src=e; console.info('aaa:', e) } });

}       

var x = new Image;
x.src="-.jpg";

document.body.append(x);

</script>
</body>
</html>     

您需要首先提取“原始”setter 和 getter 並自己調用它們:

 // get the original descriptor const desc = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src"); Object.defineProperty( HTMLImageElement.prototype, "src", {...desc, get: function() { console.log(this.__src); // call the original getter return desc.get.call(this); }, set: function(e) { if (e.includes('replacemask')) { e = e.replace('replacemask', 'demonstration_1.png'); } // get the original setter desc.set.call(this, e); console.info('aaa:', e) } }); var x = new Image; x.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_replacemask"; document.body.append(x);

但是請注意,這不是更新 HTMLImageElement 的當前源的唯一方法。 您有明顯的setAttribute ,但也有不太明顯的srcset<picture><source>案例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM