Use a hidden
<iframe>
instead of a new window.
javascript - Creating an iframe with given HTML dynamically - Stack Overflow[
^]
function setIframeHTML(iframe, html) {
if (typeof iframe.srcdoc !== 'undefined') {
iframe.srcdoc = html;
} else {
iframe.sandbox = 'allow-same-origin';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
}
}
function printDocument(html) {
const iframe = document.createElement('iframe');
iframe.sandbox = '';
iframe.style.display = "none";
document.body.appendChild(iframe);
const script = "script";
setIframeHTML(iframe, `<html><body>${html}<${script}>document.addEventListener("load", () => window.print());</${script}></html>`);
}
const html = `
<style type="text/css">
@font-face { font-family: Proxima Nova; src: url("Address/ProximaNovaFont.otf"); }
@font-face { font-family: Poppins; src: url("Address/Poppins-Regular.ttf"); }
</style>
<form class="form-container" id="container">
<div class="PrintOnly">
<div style="display: flex; align-items: center;" id="mainHeaders">
<img src="Address.logo4.svg" alt="logo" class="logo">
<hr class="hr-hor">
<h2 class="main-color" style="margin-top: 20px;"> information </h2>
</div>
<hr class="hr-header">
<div>
<div style="display: flex; align-items: center; padding-top: 0px">
<p class="main-color"> ID:</p>
<p class="secondary-color" style="margin-left: 8px">${NatId}</p>
<p class="main-color" style="margin-left: 61px">Date of birth:</p>
<p class="secondary-color" style="margin-left: 8px">${dob}</p>
</div>
<div class="p-n-personal" style=" margin-top: 5px">
<p class="main-color600">
<img src="Address.Icon25.svg" alt="icon" style="float:left;margin-right: 18.5px;" class="icon">
Address
</p>
</div>
</div>
</div>
</form>
`;
printDocument(html);