Access page variables from javascript

Is there a way to access site-wide (or page) variables from Javascript?

I would like to create a redirect.shtml template. It currently looks something like this:

<extend template="base.shtml">
<head id="head">
    <meta http-equiv="refresh" content="$page.custom.get('new-location').prefix('0; url=')">
</head>
<body id="body">
    <h1 :text="$page.title.suffix(' has moved!')"></h1>
    <p>This page has moved. If you are not redirected automatically, please click the link below:</p>
    <p><a href="$page.custom.get('new-location')">Go to the new page</a></p>
</body>

I would like to add an additional <script> tag in the header, with the following content:

window.location.replace(newLocation);

(Since the JavaScript runs much quicker than the http-equiv thing takes effect, so there is no annoying flash of the old page)

Is there a way to make the newLocation variable available to JavaScript, with the same value as $page.custom.get('new-location')?

Hey, of course it’s possible :slight_smile: superhtml is just rendered into html files. So it’s up to you what content/vars you add to your JS.

<extend template="base.shtml">
<head id="head">
    <meta http-equiv="refresh" content="$page.custom.get('new-location').prefix('0; url=')">
</head>
<body id="body">
    <h1 :text="$page.title.suffix(' has moved!')"></h1>
    <p>This page has moved. If you are not redirected automatically, please click the link below:</p>
    <p><a href="$page.custom.get('new-location')">Go to the new page</a></p>

    <script data-new-location="$page.custom.get('new-location')">
        (function(){
            window.location.replace(
                document.
                    querySelector('script[data-new-location]').
                    getAttribute('data-new-location'),
            );
        })();
    </script>
</body>
1 Like

I didn’t think of using data-* attributes, that is really cool!

Two questions:

  1. What is the point of making an anonymous function and then immediately calling it?
  2. After some additional searching, I found document.currentScript. Is there any benefit of using query selectors instead of that?
  1. What is the point of making an anonymous function and then immediately calling it?

I’m an old fart, that’s how you can scope things in JS :smiley: and I’m just used to wrapping JS this way. It’s not important :wink:

  1. After some additional searching, I found document.currentScript. Is there any benefit of using query selectors instead of that?

Same. Never heard of document.currentScript but it is an HTMLScriptElement that inherits from HTMLElement. So of course, use that instead :)!

1 Like