1

I am trying to make a print browser extension using window.print() but it is not working, whereas as a separate HTML file it is working.

Below are popup.js and print.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 file is

{
  "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://*/*"
  ]
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • could you provide more details about you trying to implement it as an extension? the problem seem to be there, as the syntax seems right (and you mentioned it does work independently) – MatanyaP Dec 31 '21 at 20:17
  • Your code tries to print the extension's popup. You need to run window.print() in your content script e.g. `chrome.tabs.executeScript({code: 'window.print()'})` – wOxxOm Dec 31 '21 at 21:30
  • @wOxxOm, can you write the whole Html, js code, because I really think that out of all answers, your answer is only somewhat correct. i mean what to write in html file, js file. – Sarthak Rana Jan 01 '22 at 05:02
  • Simply replace your `window.print()` with my code. – wOxxOm Jan 01 '22 at 07:41

1 Answers1

-1

try this:

Below are script.js and file.html

 document.getElementById("btn").onclick = () => 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>
Ahmed Mera
  • 15
  • 4