浏览器扩展仅替换为1img

时间:2019-02-25 15:09:15

标签: javascript google-chrome-extension

我的扩展程序应该用单一来源的gif替换页面上的所有图像(每次单击都会生成不同的gif)。但是当遍历页面图像时,它们都用相同的gif替换。我可以看到浏览器加载了它只有一次并在所有地方都可以替换,我该如何避免呢?

  console.log("Fear me!");
let imgs=document.getElementsByTagName('img');
for(elt of imgs){
    elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif';
}

1 个答案:

答案 0 :(得分:1)

一种常用的解决方案是在URL的末尾添加一个唯一的时间戳记,以便不对其进行缓存。在这里,我只要求时间戳一次,只需为每张图片添加+1。

(原谅HTML中的内联强制性JS函数,仅用于示例)

function refresh1(){
    let imgs=document.getElementsByTagName('img');
    for(elt of imgs){
        elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif';
    }
}

function refresh2(){
    let imgs=document.getElementsByTagName('img');
    let time=(new Date()).getTime();
    for(elt of imgs){
        elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif&t=' + time;
        time++;
    }
}
img {
  width: 200px;
}
<button onclick="refresh1()">without timestamp</button>
<button onclick="refresh2()">with timestamp</button><br>
<img src=""/>
<img src=""/>

相关问题