Set charset meta tag with JavaScript

后端 未结 3 1480
再見小時候
再見小時候 2021-01-07 22:14

There\'s a bug I\'m trying to track down here: https://github.com/OscarGodson/EpicEditor/issues/184#issuecomment-8805982

Based on all the information it seems

相关标签:
3条回答
  • 2021-01-07 22:49

    You can't set the charset content attribute by setting the charset property because they don't reflect each other. In fact there is no property that reflects the charset content attribute.

    The http-equiv content attribute is reflected by the httpEquiv property so

     charsetMetaTag['httpEquiv'] = 'Content-Type';
    

    would create the meta element correctly.

    But none of this matters. The character set is established by the parser, so constructing the meta element in JavaScript after the HTML has been parsed will have no effect on the character set of the document at all.

    0 讨论(0)
  • 2021-01-07 22:57

    As Alohci said, creating charset-related meta tags from JS won't have much effect on the current page.

    In my usecase, I need to be able to serialize the current page as a string and save it to some backend. Appending a missing charset meta tag (if not present) is useful for such an usecase.

    As a side-node, don't forget that the charset metatags should be at the beginning of according to the HTML5 spec. See this answer. This simple detail has lead to an important bug in my app :)

    You should rather use:

    document.head.insertBefore(charsetMetaTag,document.head.firstChild);
    
    0 讨论(0)
  • 2021-01-07 22:57

    I agree with both @alohci and @sebastien-lorber answers.

    But just addressing your orginal issue with just getting

    <meta>
    

    using the setAttribute method

    charsetMetaTag.setAttribute("charset", "UTF-8");
    

    and following @sebastien-lorber suggestion, will output

    <meta charset="UTF-8">
    

    as first child element of head

    0 讨论(0)
提交回复
热议问题