How can I get selected text in pdf in Javascript?

狂风中的少年 提交于 2020-05-16 19:12:11

问题


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:


回答1:


There is no one generic solution for all pdf extensions. Every extention has is own API. If you work with google-chrome extension i belive it's impossible.

How to get the selected text from an embedded pdf in a web page?

https://html.developreference.com/article/23259983/How+extension+get+the+text+selected+in+chrome+pdf+viewer%EF%BC%9F




回答2:


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;
  }
});


来源:https://stackoverflow.com/questions/61076303/how-can-i-get-selected-text-in-pdf-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!