最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it safe to use window.history.replaceState() in <head>? - Stack Overflow

programmeradmin0浏览0评论

I'd like to remove the #_=_ artefact that Facebook adds to URLs when a user logs in on my website.

I'm using this script:

if (window.location.hash === '#_=_') {
    const uri = window.location.toString();
    const withNoHash = uri.substring(0, uri.indexOf('#'));
    window.history.replaceState({}, document.title, withNoHash);
}

I'd like the script to fire as soon as possible, so I've put it in the <head> and it seems to work fine on Chrome & Firefox.

Is it standardized that the window.history API is ready when the script executes in <head>?

(and document.title, by the way).

I'd like to remove the #_=_ artefact that Facebook adds to URLs when a user logs in on my website.

I'm using this script:

if (window.location.hash === '#_=_') {
    const uri = window.location.toString();
    const withNoHash = uri.substring(0, uri.indexOf('#'));
    window.history.replaceState({}, document.title, withNoHash);
}

I'd like the script to fire as soon as possible, so I've put it in the <head> and it seems to work fine on Chrome & Firefox.

Is it standardized that the window.history API is ready when the script executes in <head>?

(and document.title, by the way).

Share Improve this question edited Nov 5, 2020 at 19:35 BenMorel asked Nov 5, 2020 at 18:25 BenMorelBenMorel 36.7k52 gold badges206 silver badges337 bronze badges 9
  • 3 Frankly, I'm not sure I understand why it is a question whether any portion of the window or document API wouldn't be ready as soon as JavaScript is being executed. As far as I'm aware, there's no precedent where portions of the API need to be instantiated asynchronously before they can be utilized in code-- it makes sense that these are part of the environment and are present when the environment es up. Do you have evidence/reason to believe otherwise that inspired this question? – Alexander Nied Commented Nov 7, 2020 at 20:44
  • I am not sure I understand your question since being able to execute a script means the full range of web APIs is available in that context. Also, if the script runs currently in chrome and ff, isn't that "good enough"? maybe more context is needed – Peter Commented Nov 7, 2020 at 20:47
  • 3 @AlexanderNied Well document.head and document.body are famously null until they're parsed from the html and instantiated, but that's a part of the DOM. window APIs indeed should always be ready, unless documented otherwise. – Bergi Commented Nov 7, 2020 at 21:20
  • @all The reason that inspired this question is indeed the DOM API not being ready in <head>, hence my concern about window APIs. – BenMorel Commented Nov 7, 2020 at 22:08
  • Unrelated to the question at hand but would your current script catch the artefact if the user landed on one of your sites that already has a non-fb hash in the uri? – Joe - Check out my books Commented Nov 8, 2020 at 18:48
 |  Show 4 more ments

4 Answers 4

Reset to default 1

On the topic of window

Standard browsers implement a Window interface, from which a global window property is exposed to javascript in the documents. Subsequent navigation will load different documents in the same Window even if new tabs are opened. So the properties you use, like window.location and window.history inside your document, would be present in the Window before a user navigates to your page (from Facebook) and therefore be available to your document.

This also applies to when you directly load your page in a new browser window - the document will have access to the window property. More on Window and window here: https://developer.mozilla/en-US/docs/Web/API/Window

If you are worried about your page getting loaded by a non-standard browser, or for some reason, the window property's history and location properties are overridden, you could just do a check to see if they are available, before calling them with:

if (window && window.location && window.location.hash) {
// safely use window.location.hash here
}

But even then, the error would be suppressed by the browser on the client-side.

On the topic of using document.title with replaceState()

The specification specifies it as a string, so by design, it will return an empty string if it is not set. There are no warnings from Mozilla for using it before a document is fully loaded. More here https://developer.mozilla/en-US/docs/Web/API/Document/title

Here are some quick tests I did to see if it is in fact the case using an HTML page with no <title> tag.

<html>
    <head>
        <script>
            console.log("title", document.title)
            window.history.replaceState({}, document.title, "newHMTL.page");
        </script>
    </head>
    <body>
    Testing
    </body>
</html>

There are no errors or warnings as expected.

On the topic of replaceState

The specification points out that most browsers ignore the title / document.title parameter that you pass to replaceState:

Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state.

So while I had a page ready, some more quick tests. Setting the title to null; undefined; and a function; and then passing it to replaceState did not change the title in the history nor throw errors in Chrome when there was a <title> tag or not. So 6 tests.

<html>
    <!-- <title>title</title> -->
    <head>
    <script>
        let title = () => alert("huh?") //null; //undefined;
        console.log("Title", title);
        window.history.replaceState({}, title, "NewHTML.page");
        //works as expected
    </script>
    </head>
    <body>
    Testing
    </body>
</html>

Yes it's safe as the window object will be ready when the browser start parsing the head section.

Browser creates window > window loads document object into itself > document object render DOM > document object loads all of its resources > window object fires onload event

The head section is part of the DOM api and Document object is a property of the window object and hence the document will be loaded once the window object is ready. As the history.replaceState is part of window object, it's safe of do any script part in head section.

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView prope

It is pretty safe, but I would not use it in development without a DOMContentLoaded listener. Just to be extra safe and account for those who use older browsers, I advise that you add that listener for DOMContentLoaded or window.onload that way you won't encounter any issues on a slower loading page. Also with the window.history API, as it is a native function that requires no separate functionality, you may use that safely and immediately.
TL;DR
Add a DOMContentLoaded listener just in case.

Aloha) Yes, it's safe for you and your clients because window is a global object what is available in browser for everyone and he can be used by any human. and your function can be executed by anyone. Don't worry about security in that case ;)

发布评论

评论列表(0)

  1. 暂无评论