带有 JSON 的范围对象

2024-03-26

我正在编写一个 Chrome 扩展程序,我需要将用户在网站上选择的值传递到我的服务器。我正在使用返回范围对象的代码 window.getSelection() 。我正在使用 JSON 将范围对象传递回我的服务器,但它不起作用。我对此很陌生,但我认为问题在于您只能使用 JSON 传递文本,并且范围对象既包括 DOM 结构(不是文本)又包括实际的文本选择(这是文本) 。我对么?还有其他选择吗?

var selection = window.getSelection();
$.getJSON(url, {data:selection}, function(moot) {
    alert("done");
});

一个简单的解决方法是不序列化并发送entire选择对象,而是将起点和终点存储为 XPath(及其偏移量)。像这样的事情会做:

function makeXPath (node, currentPath) {
  /* this should suffice in HTML documents for selectable nodes, XML with namespaces needs more code */
  currentPath = currentPath || '';
  switch (node.nodeType) {
    case 3:
    case 4:
      return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
    case 1:
      return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
    case 9:
      return '/' + currentPath;
    default:
      return '';
  }
}

function restoreSelection () {
      var selection = window.getSelection();
      selection.removeAllRanges();
      var range = document.createRange();
      range.setStart(document.evaluate(selectionDetails[0], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
      range.setEnd(document.evaluate(selectionDetails[2], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
      selection.addRange(range);
  }
}

function getSelection() {
   var selection = window.getSelection();
   var range = selection.getRangeAt(0);
   var selectObj = { 
      'startXPath': makeXPath(range.startContainer), 
      'startOffset': range.startOffset, 
      'endXPath': makeXPath(range.endContainer), 
      'endOffset': range.endOffset 
   }

   return selectObj
}

尚未彻底测试,但总体思路就在这里。

资料来源: and That http://home.arcor.de/martin.honnen/javascript/storingSelection1.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 JSON 的范围对象 的相关文章