Detecting individual Unicode character support with JavaScript

后端 未结 5 796
遇见更好的自我
遇见更好的自我 2020-12-05 04:24

Is it possible to detect if the client supports a particular Unicode character or if it will be rendered as a missing glyph box?

Important: Support in as many browser

5条回答
  •  我在风中等你
    2020-12-05 05:19

    Not sure whether it can be relied upon going forward (browsers might change what is shown for unsupported characters), nor am I sure that this is optimized (as I don't have a good understanding of the ideal boundaries to measure here), but the following approach (of drawing text in canvas and inspecting the result as an image) may, if reviewed, provide a more reliable and accurate check than could checking the width. All of the code in the beginning is just browser detection which we must use since feature detection is not possible.

    (function () {
    
    // http://www.quirksmode.org/js/detect.html
    var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i=0;i

    UPDATE 1

    I tried to update for modern Firefox (to try to check for the expected hex digits within the canvas), and checking to ensure that, unlike my code above, the canvas (and pattern to match it) was just large enough to accommodate the widest character per context.measureText() (U+0BCC from my testing, though presumably dependent on font, in my case "Arial Unicode MS"). Per https://bugzilla.mozilla.org/show_bug.cgi?id=442133#c9 , however, measureText currently mistakenly responds to the zoom for only the unknown characters. Now, if only one could simulate the zoom in JavaScript canvas so as to affect these measurements (and only those measurements)...

    Code available for reference at https://gist.github.com/brettz9/1f061bb2ce06368db3e5

提交回复
热议问题