How to add a entry in history API when page open?

I need add a entry in History to close a modal when I click on back button.

function addHistory() {
    window.history.pushState("forward", null, "");
}

When I use a click button to call the function, it works, but when I call the function on page load, the entry doesn’t work when page back.

window.onload = function() {
  window.history.pushState("forward", null, "");
}