如何在 Javascript 中获取 pdf 中的选定文本? [英] How can I get selected text in pdf in Javascript?
本文介绍了如何在 Javascript 中获取 pdf 中的选定文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个 Chrome 扩展来操作 pdf 文件,所以我想在 pdf 中获取选定的文本.我该怎么做.
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.
类似的事情:
推荐答案
您可以使用内部的 内置 PDF 查看器的未记录命令.
以下是内容脚本的示例:
Here's an example of a content script:
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);
}
});
// runs code in page context to access postMessage of the embedded plugin
const script = document.createElement('script');
if (chrome.runtime.getManifest().manifest_version > 2) {
script.src = chrome.runtime.getURL('query-pdf.js');
} else {
script.textContent = `(${() => {
document.querySelector('embed').postMessage({type: 'getSelectedText'}, '*');
}})()`;
}
document.documentElement.appendChild(script);
script.remove();
});
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'getPdfSelection') {
getPdfSelectedText().then(sendResponse);
return true;
}
});
此示例假设您从弹出窗口或后台脚本发送消息:
This example assumes you send a message from the popup or background script:
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
chrome.tabs.sendMessage(tab.id, 'getPdfSelection', sel => {
// do something
});
});
另见 如何打开正确的 devtools 控制台以查看扩展脚本的输出?
manifest.json 应该公开 query-pdf.js
manifest.json should expose query-pdf.js
"web_accessible_resources": [{
"resources": ["query-pdf.js"],
"matches": ["<all_urls>"],
"use_dynamic_url": true
}]
query-pdf.js
query-pdf.js
document.querySelector('embed').postMessage({type: 'getSelectedText'}, '*')
这篇关于如何在 Javascript 中获取 pdf 中的选定文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文