skip to Main Content
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
const foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
foreignObject.appendChild(document.createElement('script'))
svg.appendChild(foreignObject);
new XMLSerializer().serializeToString(svg)
// "<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><script xmlns="http://www.w3.org/1999/xhtml"></script></foreignObject></svg>"

the code string <script> becomes to x3Cscript> and </script> becomes to x3C/script> ,the result is not right how can i fix this?

and safari works just fine

safari

chrome

use createElemetNS for all elemtes

this is strange in chrome

this is strange in chrome 2

2

Answers


  1. You do not have a problem, this is just how Chrome is displaying the information to you.


    Notice how, in your screenshot, the output is surrounded with ' characters.

    This is because Chrome is telling you that the value is a string by rendering it as a string literal.

    Inside a string, x3C means <.

    The use of an escape character is so that it can be copy/pasted into an HTML <script> element without the sequence </script> inside the string literal prematurely triggering the end of the HTML script element.


    You can get a more accurate view of what the output actually looks like by replacing the last line with:

    const src = new XMLSerializer().serializeToString(svg);
    const pre = document.createElement("pre");
    pre.textContent = src;
    document.body.appendChild(pre);
    
    Login or Signup to reply.
  2. Output your constructed SVG

    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    const foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
    foreignObject.appendChild(document.createElement('script'));
    svg.appendChild(foreignObject);
    let output = new XMLSerializer().serializeToString(svg);
    document.body.innerHTML = output.replaceAll("<","&lt;");
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    const foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
    foreignObject.appendChild(document.createElement('script'));
    svg.appendChild(foreignObject);
    let output = new XMLSerializer().serializeToString(svg);
    document.body.textContent = output;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search