首页 > 解决方案 > 浏览器扩展仅替换为 1img

问题描述

我的扩展程序应该用来自单一来源的 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';
}

标签: javascriptgoogle-chrome-extension

解决方案


一种常用的解决方案是在 URL 的末尾添加一个唯一的时间戳,这样它就不会被缓存。在这里,我只要求提供一次时间戳,然后为每张图片添加 +1。

(请原谅 HTML 中的 inline 突兀的 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=""/>


推荐阅读