Home > Blockchain >  Access SVG data from URL returned in fetch API call
Access SVG data from URL returned in fetch API call

Time:06-05

I'm using an API call to return an SVG but the request is returned as url of the SVG, I need to edit the SVG colors but cannot access the SVG inline data. This url will be different with each request

This is an example URL of the SVG returned from fetch.

url: "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=test&format=svg"

Is there any way to directly access the data within the SVG e.g paths ? Or can i create a copy of the SVG and convert it into an inline SVG?

I have seen some suggestions that are in jquery but would like to use vanilla javascript or react library.

CodePudding user response:

you can temporarily put it on a div for example then you can access HTMLElement prototype

fetch('https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=test&format=svg')
.then(res => res.text())
.then(res => {
    const holder = document.createElement('div')
    holder.innerHTML = res
    console.log(holder.querySelector('path'))
})

CodePudding user response:

You can load an external SVG file in shadowDOM, and apply styles to its shadowDOM only,
with the, 8 lines Vanilla JavaScript, <load-file> Web Component from DEV.to load content
(full code below)

Your example SVG has inline style definitions; you can not overrule those with CSS.
I added 1 line to the Web Component to delete all style attributes, for the CSS to take effect.

For a React version, just add a 6553 Bytes React Library, and some 10 more lines of code.
(and a Build step)

customElements.define("load-svg", class extends HTMLElement {
  async connectedCallback(
          src = this.getAttribute("src"),
          shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
  ) {
    shadowRoot.innerHTML = await (await fetch(src)).text();
    shadowRoot.append(...this.querySelectorAll("[shadowRoot]"));
    this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes);
    [...shadowRoot.querySelectorAll("[style]")].map(el=>el.removeAttribute("style"));
  }
})
<load-svg src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=test&format=svg">
  <style shadowRoot>
   rect {
    fill:yellow;
   }
   path {
    stroke:red;
    fill:red;
   }
  </style>
</load-svg>

  • Related