我是javascript和chrome扩展的新手,所以请对我轻松一点
我有一个chrome扩展程序,当前可处理html页面-但我也希望它能够在chrome浏览器中查看时处理在线嵌入的PDF。 因此,我试图访问内容脚本中的pdf.js库。
根据以前的帖子:Chrome Extension | How to include library in content and background scripts from cdn
加载清单
我尝试在manifest.json
中加载库pdf.js:
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["https://mozilla.github.io/pdf.js/build/pdf.js","content.js"]
}
但是当我加载chrome扩展名时,会导致错误“无法加载manifest.json”。
直接加载到内容脚本中
我还尝试使用chrome.tabs.executeScript
直接在内容脚本中加载库:
chrome.tabs.executeScript(null,{
file:"https://mozilla.github.io/pdf.js/build/pdf.js"
});
但是这会导致错误:
Error in event handler: TypeError: Cannot read property 'executeScript' of undefined at gotMessage
目前,我的chrome扩展程序设置如下: 弹出窗口中有一堆复选框和输入字段,它们将生成数据,并将通过后台脚本发送到内容脚本,以通知其行为。
我想添加一个“滴答盒”,该滴答盒实现通知加载的文档是PDF。这样,我可以在内容脚本中使用if语句将内容页面视为pdf并加载pdf.js
库。
弹出
<input id="check_id" type="checkbox" />
背景
$(function(){
if ($('#check_id').is(":checked")){
console.log('checked');
var msg = {pdf:'yes'}
}else{
var msg={pdf:'no'}
}
chrome.tabs.query({currentWindow: true, active: true},
function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, msg)
});
});
内容
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
if(message.pdf==='yes'){
chrome.tabs.executeScript(null,
{file:"https://mozilla.github.io/pdf.js/build/pdf.js"
});
PDFJS.getDocument('link to online embedded pdf').then(doc =>{
console.log("this is"+ doc._pdfInfo.numPages);
}else{
// treat as normal HTML page
}
}
因此,有人知道如何正确地在内容脚本中加载外部库并随后使用它吗?