A place to cache linked articles (think custom and personal wayback machine)
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.html 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang="fr">
  4. <!-- Has to be within the first 1024 bytes, hence before the `title` element
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset="utf-8">
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name="viewport" content="width=device-width,initial-scale=1">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>How to update the URL of a page without causing a reload using vanilla JavaScript (archive) — David Larlet</title>
  13. <meta name="description" content="Publication mise en cache pour en conserver une trace.">
  14. <!-- That good ol' feed, subscribe :). -->
  15. <link rel="alternate" type="application/atom+xml" title="Feed" href="/david/log/">
  16. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  17. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons2/apple-touch-icon.png">
  18. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons2/favicon-32x32.png">
  19. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons2/favicon-16x16.png">
  20. <link rel="manifest" href="/static/david/icons2/site.webmanifest">
  21. <link rel="mask-icon" href="/static/david/icons2/safari-pinned-tab.svg" color="#07486c">
  22. <link rel="shortcut icon" href="/static/david/icons2/favicon.ico">
  23. <meta name="msapplication-TileColor" content="#f7f7f7">
  24. <meta name="msapplication-config" content="/static/david/icons2/browserconfig.xml">
  25. <meta name="theme-color" content="#f7f7f7" media="(prefers-color-scheme: light)">
  26. <meta name="theme-color" content="#272727" media="(prefers-color-scheme: dark)">
  27. <!-- Documented, feel free to shoot an email. -->
  28. <link rel="stylesheet" href="/static/david/css/style_2021-01-20.css">
  29. <!-- See https://www.zachleat.com/web/comprehensive-webfonts/ for the trade-off. -->
  30. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  31. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  32. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  33. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  34. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  35. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  36. <script>
  37. function toggleTheme(themeName) {
  38. document.documentElement.classList.toggle(
  39. 'forced-dark',
  40. themeName === 'dark'
  41. )
  42. document.documentElement.classList.toggle(
  43. 'forced-light',
  44. themeName === 'light'
  45. )
  46. }
  47. const selectedTheme = localStorage.getItem('theme')
  48. if (selectedTheme !== 'undefined') {
  49. toggleTheme(selectedTheme)
  50. }
  51. </script>
  52. <meta name="robots" content="noindex, nofollow">
  53. <meta content="origin-when-cross-origin" name="referrer">
  54. <!-- Canonical URL for SEO purposes -->
  55. <link rel="canonical" href="https://gomakethings.com/how-to-update-the-url-of-a-page-without-causing-a-reload-using-vanilla-javascript/">
  56. <body class="remarkdown h1-underline h2-underline h3-underline em-underscore hr-center ul-star pre-tick" data-instant-intensity="viewport-all">
  57. <article>
  58. <header>
  59. <h1>How to update the URL of a page without causing a reload using vanilla JavaScript</h1>
  60. </header>
  61. <nav>
  62. <p class="center">
  63. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  64. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  65. </svg> Accueil</a> •
  66. <a href="https://gomakethings.com/how-to-update-the-url-of-a-page-without-causing-a-reload-using-vanilla-javascript/" title="Lien vers le contenu original">Source originale</a>
  67. </p>
  68. </nav>
  69. <hr>
  70. <p>Yesterday, we looked at <a href="https://gomakethings.com/how-to-create-a-search-page-for-a-static-website-with-vanilla-js/">how to build a vanilla JavaScript search feature for a static website</a>. At the end, I mentioned…</p>
  71. <blockquote>
  72. <p>Tomorrow, I’ll show you how I update the URL with the search query, and run a search automatically on page load if there’s a query in the URL.</p>
  73. </blockquote>
  74. <p>Well, today is tomorrow, so let’s dig in!</p>
  75. <p><em><strong>Note:</strong> If you haven’t yet, you should probably read yesterday’s post first, or today’s won’t make much sense.</em></p>
  76. <h2 id="updating-the-url">Updating the URL</h2>
  77. <p>In our <code>search()</code> function, we create an array of regex patterns, get an array of matching items (sorted by how many matches they have), and then render them into the UI.</p>
  78. <p>Let’s create another function, <code>updateURL()</code>, to update the URL for us. We’ll pass in the search <code>query</code> as an argument.</p>
  79. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="cm">/**
  80. </span><span class="cm"> * Search for matches
  81. </span><span class="cm"> * @param {String} query The term to search for
  82. </span><span class="cm"> */</span>
  83. <span class="kd">function</span> <span class="nx">search</span> <span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
  84. <span class="c1">// ...
  85. </span><span class="c1"></span>
  86. <span class="c1">// Display the results
  87. </span><span class="c1"></span> <span class="nx">showResults</span><span class="p">(</span><span class="nx">results</span><span class="p">);</span>
  88. <span class="c1">// Update the URL
  89. </span><span class="c1"></span> <span class="nx">updateURL</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
  90. <span class="p">}</span>
  91. </code></pre></div>
  92. <p>We’re going to use <a href="https://gomakethings.com/how-to-update-the-browser-url-without-refreshing-the-page-using-the-vanilla-js-history-api/">the <code>history.pushState()</code> method</a> to update our URL.</p>
  93. <p>This creates a new entry in the browser’s history (and updates the URL) <em>without</em> causing the page to reload. It accepts three arguments: the browser <code>state</code>, a <code>title</code> to use in the <code>document</code>, and the <code>url</code>.</p>
  94. <p>We’ll use the current <code>history.state</code>, no need to replace anything. We’ll also use the current <code>document.title</code>.</p>
  95. <p>For the <code>url</code>, we’ll combine the <code>location.origin</code> and <code>location.pathname</code>, then append the <code>?s</code> query string parameter, and use the <code>query</code> for its value. We’ll pass the <code>query</code> into the <code>encodeURI()</code> method to encode it.</p>
  96. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="cm">/**
  97. </span><span class="cm"> * Update the URL with a query string for the search string
  98. </span><span class="cm"> * @param {String} query The search query
  99. </span><span class="cm"> */</span>
  100. <span class="kd">function</span> <span class="nx">updateURL</span> <span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
  101. <span class="c1">// Create the properties
  102. </span><span class="c1"></span> <span class="kd">let</span> <span class="nx">state</span> <span class="o">=</span> <span class="nx">history</span><span class="p">.</span><span class="nx">state</span><span class="p">;</span>
  103. <span class="kd">let</span> <span class="nx">title</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">title</span><span class="p">;</span>
  104. <span class="kd">let</span> <span class="nx">url</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">origin</span> <span class="o">+</span> <span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">pathname</span> <span class="o">+</span> <span class="s1">'?s='</span> <span class="o">+</span> <span class="nb">encodeURI</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
  105. <span class="p">}</span>
  106. </code></pre></div>
  107. <p>Finally, we can pass all three into the <code>history.pushState()</code> method to update the URL.</p>
  108. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="cm">/**
  109. </span><span class="cm"> * Update the URL with a query string for the search string
  110. </span><span class="cm"> * @param {String} query The search query
  111. </span><span class="cm"> */</span>
  112. <span class="kd">function</span> <span class="nx">updateURL</span> <span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="p">{</span>
  113. <span class="c1">// Create the properties
  114. </span><span class="c1"></span> <span class="c1">// ...
  115. </span><span class="c1"></span>
  116. <span class="c1">// Update the URL
  117. </span><span class="c1"></span> <span class="nx">history</span><span class="p">.</span><span class="nx">pushState</span><span class="p">(</span><span class="nx">state</span><span class="p">,</span> <span class="nx">title</span><span class="p">,</span> <span class="nx">url</span><span class="p">);</span>
  118. <span class="p">}</span>
  119. </code></pre></div>
  120. <h2 id="running-a-search-on-page-load">Running a search on page load</h2>
  121. <p>If the URL has an <code>s</code> query string parameter when the page loads, we should also run a search immediately. This lets users bookmark search pages for later.</p>
  122. <p>First, we’ll create an <code>onload()</code> function to run immediately with the script.</p>
  123. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="c1">// Create a submit handler
  124. </span><span class="c1"></span><span class="nx">form</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'submit'</span><span class="p">,</span> <span class="nx">submitHandler</span><span class="p">);</span>
  125. <span class="c1">// Check for query strings onload
  126. </span><span class="c1"></span><span class="nx">onload</span><span class="p">();</span>
  127. </code></pre></div>
  128. <p>We’ll use <a href="https://gomakethings.com/getting-values-from-a-url-with-vanilla-js/">the <code>new URLSearchParams()</code> constructor</a> to create a <code>URLSearchParams</code> object from the <code>location.search</code> property.</p>
  129. <p>Then, we’ll use the <code>URLSearchParams.get()</code> method to look for a query string parameter with a key of <code>s</code>.</p>
  130. <p>If one is <em>not</em> found, we’ll use the <code>return</code> operator to end our function.</p>
  131. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="cm">/**
  132. </span><span class="cm"> * If there's a query string search term, search it on page load
  133. </span><span class="cm"> */</span>
  134. <span class="kd">function</span> <span class="nx">onload</span> <span class="p">()</span> <span class="p">{</span>
  135. <span class="kd">let</span> <span class="nx">query</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">URLSearchParams</span><span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">search</span><span class="p">).</span><span class="nx">get</span><span class="p">(</span><span class="s1">'s'</span><span class="p">);</span>
  136. <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">query</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
  137. <span class="p">}</span>
  138. </code></pre></div>
  139. <p>If a <code>query</code> exists, we’ll update the <code>input.value</code> property with it so that the search field contains the search <code>query</code>. Then, we’ll pass the <code>query</code> into the <code>search()</code> function to run a search.</p>
  140. <p>The <code>URLSearchParams.get()</code> method automatically decodes the parameter for us, so we don’t need to worry about that.</p>
  141. <div class="highlight"><pre class="chroma"><code class="language-js" data-lang="js"><span class="cm">/**
  142. </span><span class="cm"> * If there's a query string search term, search it on page load
  143. </span><span class="cm"> */</span>
  144. <span class="kd">function</span> <span class="nx">onload</span> <span class="p">()</span> <span class="p">{</span>
  145. <span class="kd">let</span> <span class="nx">query</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">URLSearchParams</span><span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">search</span><span class="p">).</span><span class="nx">get</span><span class="p">(</span><span class="s1">'s'</span><span class="p">);</span>
  146. <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">query</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
  147. <span class="nx">input</span><span class="p">.</span><span class="nx">value</span> <span class="o">=</span> <span class="nx">query</span><span class="p">;</span>
  148. <span class="nx">search</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>
  149. <span class="p">}</span>
  150. </code></pre></div>
  151. <p>Now, when someone reloads or revists a search page, a new search will automatically run.</p>
  152. </article>
  153. <hr>
  154. <footer>
  155. <p>
  156. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  157. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  158. </svg> Accueil</a> •
  159. <a href="/david/log/" title="Accès au flux RSS"><svg class="icon icon-rss2">
  160. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-rss2"></use>
  161. </svg> Suivre</a> •
  162. <a href="http://larlet.com" title="Go to my English profile" data-instant><svg class="icon icon-user-tie">
  163. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-user-tie"></use>
  164. </svg> Pro</a> •
  165. <a href="mailto:david%40larlet.fr" title="Envoyer un courriel"><svg class="icon icon-mail">
  166. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-mail"></use>
  167. </svg> Email</a> •
  168. <abbr class="nowrap" title="Hébergeur : Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33184162340"><svg class="icon icon-hammer2">
  169. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-hammer2"></use>
  170. </svg> Légal</abbr>
  171. </p>
  172. <template id="theme-selector">
  173. <form>
  174. <fieldset>
  175. <legend><svg class="icon icon-brightness-contrast">
  176. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-brightness-contrast"></use>
  177. </svg> Thème</legend>
  178. <label>
  179. <input type="radio" value="auto" name="chosen-color-scheme" checked> Auto
  180. </label>
  181. <label>
  182. <input type="radio" value="dark" name="chosen-color-scheme"> Foncé
  183. </label>
  184. <label>
  185. <input type="radio" value="light" name="chosen-color-scheme"> Clair
  186. </label>
  187. </fieldset>
  188. </form>
  189. </template>
  190. </footer>
  191. <script src="/static/david/js/instantpage-5.1.0.min.js" type="module"></script>
  192. <script>
  193. function loadThemeForm(templateName) {
  194. const themeSelectorTemplate = document.querySelector(templateName)
  195. const form = themeSelectorTemplate.content.firstElementChild
  196. themeSelectorTemplate.replaceWith(form)
  197. form.addEventListener('change', (e) => {
  198. const chosenColorScheme = e.target.value
  199. localStorage.setItem('theme', chosenColorScheme)
  200. toggleTheme(chosenColorScheme)
  201. })
  202. const selectedTheme = localStorage.getItem('theme')
  203. if (selectedTheme && selectedTheme !== 'undefined') {
  204. form.querySelector(`[value="${selectedTheme}"]`).checked = true
  205. }
  206. }
  207. const prefersColorSchemeDark = '(prefers-color-scheme: dark)'
  208. window.addEventListener('load', () => {
  209. let hasDarkRules = false
  210. for (const styleSheet of Array.from(document.styleSheets)) {
  211. let mediaRules = []
  212. for (const cssRule of styleSheet.cssRules) {
  213. if (cssRule.type !== CSSRule.MEDIA_RULE) {
  214. continue
  215. }
  216. // WARNING: Safari does not have/supports `conditionText`.
  217. if (cssRule.conditionText) {
  218. if (cssRule.conditionText !== prefersColorSchemeDark) {
  219. continue
  220. }
  221. } else {
  222. if (cssRule.cssText.startsWith(prefersColorSchemeDark)) {
  223. continue
  224. }
  225. }
  226. mediaRules = mediaRules.concat(Array.from(cssRule.cssRules))
  227. }
  228. // WARNING: do not try to insert a Rule to a styleSheet you are
  229. // currently iterating on, otherwise the browser will be stuck
  230. // in a infinite loop…
  231. for (const mediaRule of mediaRules) {
  232. styleSheet.insertRule(mediaRule.cssText)
  233. hasDarkRules = true
  234. }
  235. }
  236. if (hasDarkRules) {
  237. loadThemeForm('#theme-selector')
  238. }
  239. })
  240. </script>
  241. </body>
  242. </html>