将 html2pdf 导入 Firefox 扩展时出现模块错误

问题描述 投票:0回答:1

嗨,我查看了其他答案,例如https://stackoverflow.com/a/63122940/3255525

我正在尝试在 Firefox 扩展中使用 HTML2PDF,我不仅想制作当前页面的 PDF,还想制作整个网站的 PDF。 (这是 Github Pages 中的大学项目文档)

我无法克服该错误,导入声明可能仅出现在控制台中模块的顶层

我尝试了几种不同的方法来导入文件。在我的清单中我有:

{
  "manifest_version": 2,
  "name": "Newone",
  "version": "1.0",
  "description": "An extension to read all files on the Github website and convert to PDFs.",
  "icons": {
    "48": "icons/border-48.png"
  },
  "content_scripts": [
    {
      "matches": [
        "*://github.gatech.edu/pages/cs6035-tools/cs6035-tools.github.io/"
      ],
      "js": [
        "newone.js"
      ]
    }
  ],
  "background": {
    "page": "background.html"
  },
  "browser_specific_settings": {
    "gecko": {
      "id": "[email protected]"
    }
  }
}

这是我的js文件:

import html2pdf from "dist/html2pdf";

// I've also tried this approach, then attach the script to the DOM, which I omit    
// const moduleURL = chrome.runtime.getURL('/dist/html2pdf.js');

// const script = document.createElement('script');
// script.src = moduleURL;
// document.head.appendChild(script);

document.body.style.border = "5px solid red";

var element = document.body;
var opt = {
    margin:       1,
    filename:     'GTFile.pdf',
    image:        { type: 'jpeg', quality: 0.98 },
    html2canvas:  { scale: 2 },
    jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
};

var worker = html2pdf().from(element).set(opt).save();

alert("Hopefully there's a PDF file created!");

但是即使我设置了一个 HTML 文件:

<script type="module" src='./dist/html2pdf.js'></script>

我仍然收到一个错误:导入声明可能只出现在模块的顶层

我尝试进入 html2pdf.js 文件并导出

var = function html2pdf
,没有骰子。

不确定下一步是什么,感谢您的帮助!

注意:对 firefox-addon 标签感到抱歉,这就是我输入 firefox-extension 时出现的内容

javascript firefox import firefox-addon
1个回答
0
投票

Firefox 扩展目前不支持直接在内容脚本中使用 ECMAScript 模块。

1- 使用 HTML 文件中的脚本包含 html2pdf 库:

<script src='path/to/html2pdf.js'></script>

2-使用窗口全局来访问html2pdf对象:

document.body.style.border = "5px solid red";

var element = document.body;
var opt = {
    margin:       1,
    filename:     'GTFile.pdf',
    image:        { type: 'jpeg', quality: 0.98 },
    html2canvas:  { scale: 2 },
    jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
};

var worker = window.html2pdf().from(element).set(opt).save();

alert("Hopefully there's a PDF file created!");
© www.soinside.com 2019 - 2024. All rights reserved.