【问题标题】:range.surroundContents in chrome extension is disabling right clickchrome 扩展中的 range.surroundContents 禁用右键单击
【发布时间】:2018-07-10 05:26:36
【问题描述】:

我正在构建一个 chrome 扩展,其中选定的文本可以应用不同的突出显示样式。我使用范围来让这一切正常工作,我克隆范围,在它周围放置一个跨度,然后删除范围并用克隆的范围替换它。一切似乎都很好,除了我设法通过扩展触发此行为来禁用右键单击。我已将其缩小到range.surroundContents(span) 的单行,但这里是完整的代码部分:

// Determines the selected text
document.onmouseup = function() {
    var selection = document.getSelection();
    selection = getSelectedText(color);
};

// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
    var span = document.createElement('span');
    span.setAttribute('class', inputColor);

    if(document.getSelection) {
        var selection = document.getSelection();
        if(selection.rangeCount == true) {
            var range = selection.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
}

有什么办法可以解决这个问题吗?我已经尝试在问题行之后直接使用document.oncontextmenu = false,但这并没有恢复右键单击。我还尝试按照https://developer.mozilla.org/en-US/docs/Web/API/Range/surroundContents 的建议将其替换为newNode.appendChild(range.extractContents()); range.insertNode(newNode),但它并没有突出显示文本,而是将其从页面中删除。

【问题讨论】:

  • 我认为问题在于您在事件处理期间删除了单击的元素。尝试在 setTimeout 内进行。
  • @wOxxOm 完全有效。您是否碰巧知道为什么在处理过程中删除元素会禁用所有内容的右键单击?其他一切,包括左键单击,都正常工作。

标签: javascript google-chrome google-chrome-extension range right-click


【解决方案1】:

@wOxxOm 在评论中回答了我的问题,但是 setTimeout() 是有效的。因此,对于将来可能遇到类似问题的其他人:

// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
    var span = document.createElement('span');
    span.setAttribute('class', inputColor);

    if(document.getSelection) {
        var selection = document.getSelection();
        if(selection.rangeCount == true) {
            var range = selection.getRangeAt(0).cloneRange();
            setTimeout(function(){
                range.surroundContents(span);
                selection.removeAllRanges();
                selection.addRange(range);
            }, 100)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多