所以,我昨天得到了Firefox56 (Ubuntu Gnome),并且我开始尝试使用tabs.saveAsPDF()函数(Firefox 56+)。因此,在site上,他们所展示的示例是针对后台脚本的。但我只想在按下按钮的时候触发它。因此,我制作了一个按钮,并在.js文件(弹出窗口)中编写了此代码。
var savepdf = document.querySelector('.savePDF');
savepdf.addEventListener('click', saveaspdf);
function saveaspdf(){
console.log('Inside saveaspdf'); //for checking
browser.tabs.saveAsPDF({footerCenter:"hello",footerLeft:"2",footerRight:"4/10/2017",headerCenter:"Mera Baba",headerLeft:"Baba",headerRight:"Baba",marginBottom:0.5,marginLeft:0.5,marginRight:0.5,marginTop:0.5,orientation:0,paperHeight:11.0,paperSizeUnit:0,paperWidth:8.5,scaling:1,showBackgroundColors:false,showBackgroundImages:false,shrinkToFit:true})
.then((status) => {
console.log(status);
});
}当我点击按钮时,会出现保存为pdf的窗口(假设我选择了Desktop),然后我点击了保存。什么也没有发生(下载插件也不会变成蓝色),一个损坏的pdf文件被保存到我的桌面上。控制台如下所示:

因此,它会进入函数内部,但是(我不太清楚)“无法发送函数调用结果...”时有发生。关于如何解决这个问题,请帮助我。
这是我的manifest.json文件:
"permissions": [
"storage",
"<all_urls>",
"tabs",
"activeTab"
],
"browser_action": {
"default_icon": "icons/pdf.ico",
"default_title": "My pdf",
"default_popup": "popup/addsite.html"
}编辑:-
我做了一个非常简单的扩展,只包含一个background.js文件,并从this站点复制了代码。不过,这个函数似乎唯一有效的页面就是火狐的about:debugging页面。所以我不明白我错过了什么?!
发布于 2017-10-04 20:58:47
browser.tabs.saveAsPDF只能在后台脚本中工作。您需要在内容脚本和后台脚本之间进行消息传递。
所以contentscript.js:
var savepdf = document.querySelector('.savePDF');
savepdf.addEventListener('click', saveaspdf);
function saveaspdf(){
console.log('Inside saveaspdf'); //for checking
browser.runtime.sendMessage("saveCurrentPageAsUrl");
}background.js:
browser.runtime.onMessage.addListener(onMessage);
function onMessage(message) {
if(message == "saveCurrentPageAsUrl"){
saveCurrentPageAsUrl();
}
}
function saveCurrentPageAsUrl(){
browser.tabs.saveAsPDF({footerCenter:"hello",footerLeft:"2",footerRight:"4/10/2017",headerCenter:"Mera Baba",headerLeft:"Baba",headerRight:"Baba",marginBottom:0.5,marginLeft:0.5,marginRight:0.5,marginTop:0.5,orientation:0,paperHeight:11.0,paperSizeUnit:0,paperWidth:8.5,scaling:1,showBackgroundColors:false,showBackgroundImages:false,shrinkToFit:true})
.then((status) => {
console.log(status);
});
}
}一个影响Firefox57和Firefox58的bug (https://bugzilla.mozilla.org/show_bug.cgi?id=1404681)目前阻止大多数页面保存为PDF,因此应该使用getBrowserInfo (https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/getBrowserInfo)在插件中内置检查,以便在不支持(https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/notifications)时向用户显示通知。
https://stackoverflow.com/questions/46564293
复制相似问题