【问题标题】:window.print() not working in browser extension [duplicate]window.print()在浏览器扩展中不起作用[重复]
【发布时间】:2021-12-31 19:57:55
【问题描述】:

我正在尝试使用window.print() 制作一个打印浏览器扩展,但它不起作用,而作为一个单独的 HTML 文件它正在工作。

下面是popup.jsprint.html

document.getElementById("m").addEventListener("click", myFunction);

function myFunction() {
  window.print();
}
<!DOCTYPE html>
<html>

<body>
  <h2>The window.print() Method</h2>
  <button id="m"> click me </button>
</body>
<script src="popup.js">
</script>

</html>

清单文件是

{
  "manifest_version": 2,
  "name": "print",
  "version": "0.10002",
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": [
      "popup.js",
      "content.bundle.js"
    ],
    "run_at": "document_idle",
    "matches": ["https://*/*"]
  }],
  "browser_action": {
    "default_popup": "print.html"
  },
  "background": {
    "scripts": [
      "background.bundle.js",
      "background.js"
    ]
  },
  "permissions": [
    "storage",
    "https://*/*"
  ]
}

【问题讨论】:

  • 您能否提供更多有关您尝试将其作为扩展实现的详细信息?问题似乎在那里,因为语法似乎正确(你提到它确实独立工作)
  • 您的代码尝试打印扩展程序的弹出窗口。您需要在内容脚本中运行 window.print() 例如chrome.tabs.executeScript({code: 'window.print()'})
  • @wOxxOm,你能写出整个Html,js代码吗,因为我真的认为在所有答案中,你的答案只是有点正确。我的意思是在html文件,js文件中写什么。
  • 只需用我的代码替换您的window.print()

标签: javascript html google-chrome-extension popup browser-extension


【解决方案1】:

试试这个:

下面是script.jsfile.html

 document.getElementById("btn").onclick = () =&gt; window.print();
<!DOCTYPE html>
<html>
<body>

<p>Click the button to print the current page.</p>

<button id = "btn" >Print this page</button>

<script src = "script.js" ></script>

</body>
</html>

【讨论】:

  • 是的。这将起作用,因为您在插入 &lt;script&gt; 标记时犯了一个错误,您必须将其放在正文或 &lt;head&gt; 标记中
  • 这个“错误”没有任何意义,因为脚本标签在 head/body 之外的工作原理是一样的。
  • @AhmedMera,没有这个代码不起作用。 ☹
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2016-11-02
  • 2015-12-14
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
相关资源
最近更新 更多