Replace background-images with <img> tag

Replaces elements with "background-image" inline style with a separate img tag with src pointing to that image. That allows right-click on the image to copy URL & share conveniently.

  1. // ==UserScript==
  2. // @name Replace background-images with <img> tag
  3. // @description Replaces elements with "background-image" inline style with a separate img tag with src pointing to that image. That allows right-click on the image to copy URL & share conveniently.
  4. // @namespace replbackgroundiwithimgtag
  5. // @version 1.0.4
  6. // @author k3abird
  7. // @include *
  8. // @exclude https://steamcommunity.com/*
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. const els = document.querySelectorAll("[style]");
  15. let reURL = /url\(['"]*(.*?)['"]*\)/;
  16.  
  17. let replacedCnt = 0;
  18. els.forEach((el) => {
  19. // skip img tags
  20. if (el.tagName == "IMG") {
  21. return;
  22. }
  23. const elSt = el.style;
  24. if (elSt.backgroundImage != "" && elSt.backgroundPosition == "") {
  25. const m = el.style.backgroundImage.match(reURL);
  26. if (m != null && m.length > 1) {
  27. const cs = window.getComputedStyle(el);
  28. //if (cs.backgroundSize != "cover") {
  29. // return // does not have cover, do not replace
  30. //}
  31. // remove original background image
  32. elSt.backgroundImage = "";
  33. // ensure position relative on parent
  34. elSt.position = "relative";
  35. // append a child <img>
  36. const img = document.createElement("img")
  37. img.src = m[1];
  38. img.style.position = "absolute";
  39. img.style.display = "inline";
  40. img.style.visibility = "visible";
  41. img.style.left = img.style.top = "0";
  42. img.style.zIndex = -1;
  43. // img.style.width = img.style.height = "100%";
  44. // if (cs.width != "" && cs.width != "0px") {
  45. // img.style.width = cs.width;
  46. // } else {
  47. // img.style.width = "100%";
  48. // }
  49. if (cs.height != "" && cs.height != "0px") {
  50. img.style.height = cs.height;
  51. } else {
  52. img.style.height = "100%";
  53. }
  54. el.appendChild(img);
  55. replacedCnt++;
  56. }
  57. }
  58. });
  59.  
  60. if (replacedCnt > 0) {
  61. console.log("k3a: fixed "+replacedCnt+"/"+els.length+" elements with background-image by appending img child");
  62. }
  63. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址