How to stop extensions/add ons like grammarly on contenteditable editors

前端 未结 4 1056
-上瘾入骨i
-上瘾入骨i 2020-12-14 00:39

We are making contenteditable editor. Wondering how to stop extensions like grammarly (if enabled) on editor page using javascript as these extensions insert their own html

4条回答
  •  孤城傲影
    2020-12-14 01:33

    I had a similar problem: my webapp needs know the exact representation of the DOM tree.

    Grammarly's extension, however, adds random bits of custom HTML into the DOM tree. I solved the problem by disallowing grammarly, or anything, from modifying the HTML.

    I use code similar to @jbranj. But I remove any added HTML from the page. I see a minor slow down on first click into the textarea on safari but it's fine otherwise.

    var observer = new MutationObserver(function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                for (let node of mutation.addedNodes) node.remove()
            }
        }
    })
    

    I run observer.observe(document, { attributes: false, childList: true, subtree: true }) when I want to prevent HTML additions. And observer.disconnect() when I want to allow it so I can modify the DOM myself.

    (I'm not entirely sure why but both childList and subTree need to be true when you enable the observer.)


    Edit:

    Because some anti-virus software can hang the browser if you straight out refuse to let them inject scripts in your html:

    var added_nodes = []
    var observer = new MutationObserver(function (mutationsList, observer) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                for (let node of mutation.addedNodes) added_nodes.push(node)
            }
        }
    })
    

    Then later added_nodes.forEach(n => n.remove()) to remove all the injected tags.

提交回复
热议问题