简体   繁体   中英

function not working with using window.location.href

The function html2pdf(element) (generates a pdf of the page) works fine. After executing the function, i want to direct to an other page. In my case adding window.location.href[...] the page is just redirecting to the next page but the function html2pdf is not working anymore.

<script>
  $(function() {});
  function printPDF() {
    var element = document.getElementById("element-to-print");
    var opt = {
      margin: 1,
      filename: "EFS10Laptop.pdf",
      image: { type: "jpeg", quality: 1.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: "in", format: "letter", orientation: "portrait" }
    };

    // New Promise-based usage:
    //html2pdf().from(element).set(opt).save();
    html2pdf(element);
    window.location.href = "index.php";
  }
</script>

Ankur was right - html2pdf , either used with or without its promise based API, is asynchronous in nature, so it won't stop your code from continuing while it is processing the request, and since setting window.location.href is near instantaneous, the redirect is reached before html2pdf has a chance to complete.

Because html2pdf has the promise based API, this is very easy to avoid - simply wait until the save promise resolves to redirect, like so:

html2pdf().from(element).set(opt).save().then(()=>{
    window.location.href = "index.php";
});

Note that this still redirects the user while the save dialog is still open. I don't see a promise listed for when this is closed in the documentation (probably because the JS side does not know about it), but it doesn't prevent html2pdf from working since the generation of the file blob occurs before the page redirects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM