我正在使用Chrome扩展程序,该扩展程序将从选择中提取纯文本网址, 但选择将始终是网址的一小部分,所以我需要左右扫描。 我基本上需要从innerText中提取500个字符,因为 我不想解析HTML元素,也不想重新组合textContent。
这是我到目前为止所做的,它运作得很好,但我觉得有更好的方法 没有修改文档对象,然后将其恢复到原始状态......
// create a random 8 digit number - or bigger since we don't want duplicates
var randId = Math.floor(Math.random()*(90000000)+10000000);
var selection = document.getSelection();
var selectionRange = selection.getRangeAt(0);
// backup content, and then clone selection the user has made
var selectionContents = selectionRange.cloneContents();
var selectionContentsTxt = selectionContents.textContent;
// add random number to previous selection, this will expand selection
selectionContents.textContent = randId;
selectionRange.insertNode(selectionContents);
// find the random number in the document (in innerText in document.body)
var everything = document.body.innerText;
var offset = everything.indexOf(randId);
// restore backed up content to original state,- replace the selection
selectionContents = selectionRange.extractContents();
selectionContents.textContent = selectionContentsTxt;
selectionRange.insertNode(selectionContents);
// now we have the selection location offset in document.body.innerText
everything = document.body.innerText;
var extract = everything.substring(offset-250, offset+250);
extract保存提取的文本,包含换行符等,由浏览器评估。 顺便说一下,这只是Chrome,所以我根本不需要交叉兼容。 现在我可以解析选择 - 从中间到边缘找到网址, 请注意,从中间开始解析很重要,所以我没有提取 来自我的getSelection()的parentNode的innerText,而不知道偏移...
有更好的方法吗?也许将整个文档复制到DOMParser, 但是,如何将原始文档中的getSelection应用于它?
------更新------
我已经简化了上面的代码(忘了提到我正在使用鼠标点击,所以我检测到了事件 单击,双击以选择一些文本),现在它找到了caretOffset document.body.innerText但它仍然修改文档然后恢复它, 所以仍然想着一个更好的方法来做到这一点。 我想知道insertNode和deleteContents在某种程度上是不是很糟糕?
var randId = Math.floor(Math.random()*(90000000)+10000000);
var range = document.caretRangeFromPoint(event.clientX, event.clientY);
range.insertNode(document.createTextNode(randId));
var everything = document.body.innerText;
var offset = everything.indexOf(randId);
range.deleteContents();
var everything = document.body.innerText;
var extract = everything.substring(offset-250, offset+250);
document.getSelection().anchorNode.parentNode.normalize();
有什么想法吗?