我正在编写Chrome扩展程序,我想在tech.io的代码部分中选择所选文本,例如:https://prnt.sc/hhfkwu上的https://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网站上使用此特定代码部分?
答案 0 :(得分:0)
问题是Ace编辑器。虽然看起来您在该框中选择文字,但它实际上是绘制看起来像选择的框,以便正确格式化下面的颜色。
window.getSelection
不会产生任何结果,因为实际上没有选择。
您可能需要检查document.activeElement
以查看它是否为ace编辑器,然后使用this answer中的解决方案:
最好使用editor.getSelectedText()代替。