简体   繁体   English

如何使我的 chrome 扩展程序正常工作?

[英]How do I make my chrome extension so that it works correct?

I am making a Chrome extension so you can download images when clicking on them.我正在制作一个 Chrome 扩展程序,因此您可以在点击图片时下载图片。 The problem is that it is a bit buggy, so any help would be awesome.问题是它有点问题,所以任何帮助都会很棒。 Here is the Javascript:这是Javascript:

var myImg = document.querySelector('img');
myImg.addEventListener("click", () => {
  var a = document.createElement('a');
  a.href = myImg.src;
  a.download = myImg.src;
  document.body.appendChild(a);
  a.click();
});

I would assume that maybe you should add an id to the image that the user clicks on, then download the value of the id.我认为也许您应该为用户单击的图像添加一个 id,然后下载该 id 的值。 But I am not sure how to do that.但我不知道该怎么做。

If you want to click on any img , you will want to use querySelectorAll to capture ALL images on the page, querySelector just grabs one.如果您想单击任何img ,您将需要使用querySelectorAll来捕获页面上的所有图像,而querySelector只抓取一张。

var myImgs = document.querySelectorAll('img');
myImgs.forEach(function(img) {
  img.addEventListener("click", (el) => {
    var a = document.createElement('a');
    a.href = el.target.src;
    a.download = el.target.src;
    document.body.appendChild(a);
    a.click();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM