How can I get selected text in pdf in Javascript?

后端 未结 2 463
甜味超标
甜味超标 2020-12-12 00:32

I\'m writing a Chrome Extention to manipulate pdf file so I want to get selected text in the pdf. How can I do that.

Some thing like that:

2条回答
  •  庸人自扰
    2020-12-12 00:43

    You can use the internal undocumented commands of the built-in PDF viewer.
    To access it your content script should do it in page context:

    function getPdfSelectedText() {
      return new Promise(resolve => {
        window.addEventListener('message', function onMessage(e) {
          if (e.origin === 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai' &&
              e.data && e.data.type === 'getSelectedTextReply') {
            window.removeEventListener('message', onMessage);
            resolve(e.data.selectedText);
          }
        });
        const script = document.createElement('script');
        document.documentElement.appendChild(script).text =
          "document.querySelector('embed').postMessage({type: 'getSelectedText'}, '*')";
        script.remove();
      });
    }
    
    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      if (msg === 'getPdfSelection') {
        getPdfSelectedText().then(sendResponse);
        return true;
      }
    });
    

提交回复
热议问题