基本構文
history.replaceState(null, null, <URLに追加したい文字列>);
実装例
まず、index.html
とindex.js
に以下のように記述する。
index.html
<label for="textInput">Path:</label>
<input type="text" id="textInput" />
<script src="index.js"></script>
index.js
const textInput = document.getElementById("textInput");
textInput.addEventListener("input", () => {
const path = '/' + textInput.value;
history.replaceState(null, null, path);
});
次に、ターミナルでindex.js
があるディレクトリに行き、以下の好きな方でサーバーを立ち上げてアクセスすると、入力した値がURLに反映されるのが確認できる。
python
以下を実行し、localhost:8000をブラウザで開く。
python3 -m http.server 8000
npx
以下を実行して、表示されたURLを開く。
npx serve -s . -l 8000