【问题标题】:Get selected text from tech.io code section从 tech.io 代码部分获取选定的文本
【发布时间】:2018-05-14 21:31:20
【问题描述】:

我正在编写一个 chrome 扩展程序,我想在 tech.io 的代码部分中选取选定的文本,例如:https://prnt.sc/hhfkwuhttps://tech.io/playgrounds/347/javascript-promises-mastering-the-asynchronous/what-is-asynchronous-in-javascript

我有这个功能在任何其他网站上几乎都可以使用,但在这里无法正常工作,它返回空字符串或一些奇怪的 unicode 字符:

function getSelectedText() {
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
    (activeElTagName == "textarea") || (activeElTagName == "input" &&
        /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
    (typeof activeEl.selectionStart == "number")
) {
    text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
    text = window.getSelection().toString();
}
    return text;
}

我应该如何更改它才能在 tech.io 网站上的这个特定代码部分工作?

【问题讨论】:

    标签: javascript html dom textselection


    【解决方案1】:

    问题在于 Ace 编辑器。虽然它看起来像是您在该框中选择文本,但实际上是在绘制看起来像选择的框,以便正确格式化下面的颜色。

    window.getSelection 不会产生任何结果,因为实际上不存在任何选择。

    您可能需要检查 document.activeElement 以查看它是否是 ace 编辑器,然后使用来自 this answer 的解决方案:

    最好改用 editor.getSelectedText()。

    【讨论】:

    • 感谢您的反馈,但我如何获得对编辑器的参考?我假设我必须将 ace.js 作为内容脚本加载,但接下来呢?
    • 好的,我使用此代码editor = ace.edit(aceEditorElement); 获得了editor 的引用,之后我能够获得选定的文本,但是它弄乱了编辑器的布局,看起来现在像这样:prnt.sc/hhg7m6
    • 编辑您的原始问题,并发布更新的答案,我们可以进一步协助@kecman
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多