I am not familiar with Javascript, and would be grateful if you could enlighten me regarding the following observation.
I have this Javascript function which should navigate to a page with param string appended. For example:
savebuttonClick() {
window.open(encodeURI("/lightning/n/Test_Win_Open_Child#Id=123"),"_self");
}
However, the above script would navigate to the correct URL, but with a blank page displayed. The page would load its content as expected, upon a manually refresh of the browser tab.
Changing the scripts by constructing the URL with the window.location.href property first before navigating with the window.open() method would addressed the issue. The page will be displayed as expected, and the parameter (Id)'s value (123) will be passed to the page:
window.location.href = encodeURI("/lightning/n/Test_Win_Open_Child#Id=123");
window.open(window.location.href,"_self");
Or, replacing the hash(#) with question mark (?) would also work:
window.open(encodeURI("/lightning/n/Test_Win_Open_Child?Id=123"),"_self");
Can someone please help explain the above observation?
Thank you very much!
You've supplied a relative URL to window.open
:
encodeURI("/lightning/n/Test_Win_Open_Child#Id=123")
which evaluates to "/lightning/n/Test_Win_Open_Child#Id=123" in any case.
window.open
opens a page with the url "about:blank" by default. A relative url applied to about:blank
is still a blank page: exactly what you first see.
Here's the tricky bit.
The base url of a page opened with about: blank
is the url of the opener. Case in point, if you document.write
content to an opened page that contains a link such as #
to go to the top of the document, taking the link opens the opener page at the top, instead of scrolling to the top of the opened page. (IMHO this a bug but I digress).
If you reload the opened page, the relative url of the opened page is resolved against the url of the opener page, as reported in the post.
Predictive confirmation
Supply an absolute url to window.open
instead of a relative url.
PostScipt
Using the hash tag in a URL provides a fragment identifier to browsers, but does not require them to reload a page from the server.
Providing a query component, introduced by ?
, does require browsers to reload the page from the server, which requires an absolute URL. Resolving a relative url against the opened pages base url (not "about:blank") would cause reloading the opened page with the intended URL.