Skip to content

Commit 46f4d47

Browse files
committed
Add popstate listener to handle browser navigation and language switching
- Add popstate event listener to properly handle browser back/forward navigation - Ensure URL parameters are correctly parsed when switching between languages - Prevent unwanted redirects during language switching by properly handling location changes - Improve handling of URL format variations during navigation
1 parent 2598b0e commit 46f4d47

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

docs/src/pages/example-detail.tsx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,49 @@ export default function ExampleDetail() {
182182
handleLocationChange();
183183
}, [location.pathname, location.search, EXAMPLES_CONFIG, exampleId]);
184184

185+
// 监听浏览器的 popstate 事件,处理前进后退和语言切换
186+
useEffect(() => {
187+
const handlePopState = () => {
188+
// URL发生变化时重新解析参数
189+
const urlParams = new URLSearchParams(location.search);
190+
let urlExampleId = urlParams.get("id");
191+
192+
if (!urlExampleId) {
193+
const pathSegments = location.pathname.split('/');
194+
for (let i = 0; i < pathSegments.length; i++) {
195+
if (pathSegments[i] === 'example-detail' && i + 1 < pathSegments.length) {
196+
const potentialId = pathSegments[i + 1];
197+
if (EXAMPLES_CONFIG.some(ex => ex.id === potentialId)) {
198+
urlExampleId = potentialId;
199+
break;
200+
}
201+
}
202+
}
203+
}
204+
205+
if (!urlExampleId) {
206+
urlExampleId = "hello-world";
207+
}
208+
209+
const targetExample = EXAMPLES_CONFIG.find(ex => ex.id === urlExampleId) || EXAMPLES_CONFIG[0];
210+
if (targetExample.id !== exampleId) {
211+
setExampleId(targetExample.id);
212+
setCode(targetExample.code);
213+
214+
setTimeout(() => {
215+
if (previewRef.current) {
216+
runCodeWithContent(targetExample.code);
217+
}
218+
}, 0);
219+
}
220+
};
221+
222+
window.addEventListener('popstate', handlePopState);
223+
return () => {
224+
window.removeEventListener('popstate', handlePopState);
225+
};
226+
}, [location.pathname, location.search, EXAMPLES_CONFIG, exampleId]);
227+
185228
// 监听主题变化
186229
useEffect(() => {
187230
const handleThemeChange = () => {

0 commit comments

Comments
 (0)