Skip to content

Commit

Permalink
change url addListener
Browse files Browse the repository at this point in the history
  • Loading branch information
wangyantong2000 committed Nov 12, 2024
1 parent d7eaecc commit 3c38bbc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 25 deletions.
5 changes: 5 additions & 0 deletions src/pages/Background/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url) {
chrome.tabs.sendMessage(tabId, { type: 'urlChanged', url: changeInfo.url });
}
});
40 changes: 15 additions & 25 deletions src/pages/ContentScripts/features/fast-pr/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,30 +55,21 @@ const init = async (matchedUrl: MatchedUrl | null) => {
document.body.appendChild(container);
}
};
const observeUrlChanges = () => {
let lastUrl = window.location.href;
const checkUrlChange = () => {
const currentUrl = window.location.href;
if (currentUrl !== lastUrl) {
lastUrl = currentUrl;
const existingContainer = document.getElementById(featureId);
if (existingContainer) {
existingContainer.remove();
}
const iframe = document.getElementById('sandboxFrame') as HTMLIFrameElement;
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage({ command: 'matchUrl', url: currentUrl }, '*');
}
}
};
const observer = new MutationObserver(checkUrlChange);
observer.observe(document.body, {
childList: true,
subtree: true,
});
setInterval(checkUrlChange, 1000);
};

chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'urlChanged') {
handleUrlChange(message.url);
}
});
function handleUrlChange(url: string) {
const existingContainer = document.getElementById(featureId);
if (existingContainer) {
existingContainer.remove();
}
const iframe = document.getElementById('sandboxFrame') as HTMLIFrameElement;
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage({ command: 'matchUrl', url: url }, '*');
}
}
window.addEventListener('message', (event: MessageEvent) => {
if (event.data && event.data.matchedUrl) {
init(event.data.matchedUrl);
Expand All @@ -102,6 +93,5 @@ features.add(featureId, {
}
}, 500);
};
observeUrlChanges();
},
});

0 comments on commit 3c38bbc

Please sign in to comment.