Inline SVG Replacer

Replace all img tags with src as an SVG file into inline SVG tags

  1. // ==UserScript==
  2. // @name Inline SVG Replacer
  3. // @namespace https://mkpo.li/
  4. // @version 0.1.1
  5. // @description Replace all img tags with src as an SVG file into inline SVG tags
  6. // @author mkpoli
  7. // @match *://*/*
  8. // @exclude *://*.google.*/*
  9. // @grant none
  10. // @license CC0
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15. const isNonSvgImage = (img) => {
  16. const ext = img.src.split('.').pop();
  17. return ext && ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif', 'apng', 'tiff', 'tif'].includes(ext);
  18. }
  19. const isSvgResponse = (response) => {
  20. const contentType = response.headers.get('Content-Type');
  21. return contentType && contentType.includes('image/svg+xml');
  22. };
  23. console.log("hello2")
  24. document.querySelectorAll('img').forEach(async img => {
  25. if (isNonSvgImage(img)) return;
  26. console.log("replacing", img)
  27. try {
  28. const response = await fetch(img.src);
  29. if (isSvgResponse(response)) {
  30. const svgText = await response.text();
  31. const parser = new DOMParser();
  32. const svgDoc = parser.parseFromString(svgText, "image/svg+xml");
  33. const inlineSvg = svgDoc.querySelector('svg');
  34.  
  35. if (inlineSvg) {
  36. Array.from(img.attributes).forEach(attr => {
  37. inlineSvg.setAttribute(attr.name, attr.value);
  38. });
  39.  
  40. img.replaceWith(inlineSvg);
  41. }
  42. }
  43. } catch (error) {
  44. console.error('Error inlining SVG:', error);
  45. }
  46. });
  47. })();

QingJ © 2025

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