我正在编写一个 Chrome 扩展来操作 pdf 文件,所以我想获取 pdf 中选定的文本。我怎样才能做到这一点。
像这样的东西:
![enter image description here](https://i.stack.imgur.com/k9Vxw.png)
您可以使用内部未记录的命令内置 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
});
});
也可以看看如何打开正确的开发工具控制台来查看扩展脚本的输出?
Manifest V3 扩展也需要这个:
-
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'}, '*')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)