Skip to content

Commit 31cd1c4

Browse files
authored
Merge pull request #70 from Setono/vv/bug-fix/53
Add history state handling
2 parents 45903de + d315edb commit 31cd1c4

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/Resources/public/js/search.js

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,18 @@ class SearchManager {
5959
});
6060

6161
this.#initializeForm();
62+
63+
window.addEventListener('popstate', (event) => {
64+
// Handle the navigation event (back/forward button)
65+
if (event.state?.searchContent) {
66+
const content = event.state.searchContent;
67+
const existingContent = document.querySelector(this.#options.contentSelector);
68+
69+
if (content && existingContent) {
70+
existingContent.innerHTML = content;
71+
}
72+
}
73+
});
6274
}
6375

6476
#initializeForm() {
@@ -117,17 +129,15 @@ class SearchManager {
117129
}
118130

119131
const text = await response.text();
120-
const parser = new DOMParser();
121-
const doc = parser.parseFromString(text, 'text/html');
122-
const newContent = doc.querySelector(this.#options.contentSelector);
132+
const newContent = this.parseResponseContent(text, this.#options.contentSelector);
123133
const existingContent = document.querySelector(this.#options.contentSelector);
124134

125135
if (newContent && existingContent) {
126136
existingContent.replaceWith(newContent);
127137
this.#initializeForm();
128138
}
129139

130-
history.pushState(null, '', url);
140+
history.pushState({ searchContent: newContent.innerHTML}, '', url);
131141
} catch (error) {
132142
console.error('Error fetching search results:', error);
133143
} finally {
@@ -158,6 +168,13 @@ class SearchManager {
158168
}
159169
}
160170

171+
parseResponseContent(html, selector) {
172+
const parser = new DOMParser();
173+
const doc = parser.parseFromString(html, 'text/html');
174+
175+
return doc.querySelector(selector);
176+
}
177+
161178
/**
162179
* @param {HTMLInputElement} field
163180
* @return {boolean}

0 commit comments

Comments
 (0)