capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.33k stars 200 forks source link

Prevent to exit / fail the process #1024

Open 2peter3 opened 1 year ago

2peter3 commented 1 year ago

Describe the bug It looks like, it isnt possible to catch Errors.

To Reproduce Steps to reproduce the behavior:

const got = require("got");
const { Window } = require("happy-dom");

async function fetchAndRender() {
  const url = "https://klaviyo.com";
  const window = new Window({
    url: url,
    width: 1024,
    height: 768,
  });
  const document = window.document;
  window.location.href = url;
  window.location.origin = url;
  try {
    const response = await got(url);
    document.body.innerHTML = response.body;
    await window.happyDOM.whenAsyncComplete();
    window.happyDOM.onerror = console.log;
    window.location.href = url;
    window.happyDOM.setURL(url);
    window.onerror = console.log;
    window.onload = console.log;

    window.addEventListener("load", () => {
      console.log("Page fully loaded");
    });
   console.log("done");
  } catch (error) {
    console.error("Error fetching the content:", error.message);
  }
}

fetchAndRender();

Device:

The text "done" will not be written

capricorn86 commented 1 year ago

Hi @2peter3! :slightly_smiling_face:

I believe that an error occur inside the try block which stops the execution of the rest of the code in the try block. It ends up in the catch block instead.

I noticed that you write the response of the page to document.body.innerHTML. Setting innerHTML will not execute any script in the HTML and I assume that you want to write the entire document HTML?

Setting "location.href" is not necessary if you send in "url" as an option to the Window constructor. "location.origin" is just a part of the URL (location.href) and is also not necessary to set.

Please try to write your code like this and see if it solves your problem:

const got = require("got");
const { Window } = require("happy-dom");

async function fetchAndRender() {
    const url = "https://klaviyo.com";
    const window = new Window({
        url: url,
        width: 1024,
        height: 768,
    });
    const document = window.document;
    let response;

    try {
        response = await got(url);
    } catch (error) {
        console.error("Error fetching the content:", error.message);
    }

    window.addEventListener("error", (event) => {
        console.log("Error", event.error.message);
    });

    window.addEventListener("load", () => {
        console.log("Page fully loaded");
    });

        if(response && response.body) {
        document.write(response.body);
    }

    await window.happyDOM.whenAsyncComplete();

    console.log("done");
}

fetchAndRender();