如何在 Javascript 中获取 pdf 中的选定文本?
IT技术
javascript
google-chrome-extension
2021-02-15 21:41:21
2个回答
没有一种适用于所有 pdf 扩展的通用解决方案。每个扩展都有自己的 API。如果您使用 google-chrome 扩展程序,我相信这是不可能的。
您可以使用内置 PDF 查看器的内部未记录命令。
这是内容脚本的示例:
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;
}
});
此示例假设您从弹出窗口或后台脚本发送消息:
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
chrome.tabs.sendMessage(tab.id, 'getPdfSelection', sel => {
// do something
});
});
另请参阅如何打开正确的 devtools 控制台以查看扩展脚本的输出?
ManifestV3 扩展也需要这个:
manifest.json 应该公开 query-pdf.js
"web_accessible_resources": [{ "resources": ["query-pdf.js"], "matches": ["<all_urls>"], "use_dynamic_url": true }]查询-pdf.js
document.querySelector('embed').postMessage({type: 'getSelectedText'}, '*')
