CreateTextRange is not working in Chrome

后端 未结 4 1818
南方客
南方客 2020-12-03 11:17

In this code, createRange is not working in Chrome. In IE it is working. Please help how to rectify in this. Is there any other property to work like create ran

相关标签:
4条回答
  • 2020-12-03 11:32

    CreateTextRange is a Microsoft specific function, but there is an easy work around.

    Use createRange instead as in this post for example:

    if (document.selection) { //IE
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) { //others
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
    }
    
    0 讨论(0)
  • 2020-12-03 11:33

    As of March 31, 2020. This works for mocking JSDOM for jest unit tests

    (window as any).global.document.createRange = () => {
        return {
            setEnd: () => {},
            setStart: () => {},
            getBoundingClientRect: () => {},
            getClientRects: () => []
        };
    };
    
    0 讨论(0)
  • 2020-12-03 11:35

    I had this issue with node's JSDOM and codemirror (which attempts to use document.createRange)

    It happens because document.createRange (chrome) does not exist ATM on JSDOM and so it tries to use document.body.createTextRange (IE) instead and falls over.

    To fix this I had to stub the document.createRange function in my unit test setup as follows:

    global.document.createRange = () => {
      return {
        setEnd: () => {},
        setStart: () => {},
        getBoundingClientRect: () => {}
      }
    }
    

    There is talk about JSDOM polyfilling document.createRange:

    See https://github.com/tmpvar/jsdom/issues/399

    At the time of writing this has not yet happened.

    0 讨论(0)
  • 2020-12-03 11:37

    createTextRange is only in IE.

    Have a look at this one http://help.dottoro.com/ljrvjsfe.php

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