PHP实现OAuth2获取Access Token后关闭登录弹窗的问题
Hey Dennis, I see exactly where you're stuck here—your current polling approach is hitting browser same-origin policy walls, which is why you're getting those "Blocked a frame with origin..." errors. Let's fix this properly without messy polling.
Why Your Current Code Fails
The browser blocks your main window (running on http://localhost) from accessing the popup's location or document because the popup starts on https://api-oauth2.city.be—a completely different origin. Polling like this will always throw errors until the popup redirects back to your localhost callback, but even then, it's inefficient and clunky.
The Right Approach: Let the Callback Page Trigger Actions
Since your redirect URI points back to your own localhost (http://localhost/codeigniter/login/city/aProfielCallback), that callback page shares the same origin as your main window. This means the popup can safely communicate with the main window using window.opener to trigger a refresh, then close itself automatically.
Step 1: Simplify the Main Window Button Code
You can remove the polling entirely—no need for the CheckLoginStatus function anymore:
$('#customBtnAprofielLogin').click(function () { const signinWin = window.open( "https://api-oauth2.city.be/v1/authorize?client_id=xxx&redirect_uri=http://localhost/codeigniter/login/city/aProfielCallback&lng=nl&scope=username+name+avatar+email+phone&service=city-aprofiel-v1&response_type=code", "SignIn", "width=972,height=660,modal=yes,alwaysRaised=yes" ); signinWin.focus(); return false; });
Step 2: Update Your Callback Page
Once your aProfielCallback page finishes handling the OAuth2 code exchange and retrieves the Access Token, add this script to the page:
// After successfully getting the Access Token (your existing token-handling logic here) // Notify the main window to refresh and use the new token if (window.opener && !window.opener.closed) { window.opener.location.reload(); } // Close the popup immediately window.close();
Why This Works
- No cross-origin issues: The callback page runs on
localhost, same as your main window, sowindow.openeris allowed to access the main window'slocationobject without restrictions. - Cleaner flow: Instead of polling for changes, the popup takes action the moment the auth flow completes.
- No console errors: You eliminate the repeated blocked frame errors entirely.
Quick Notes to Avoid Issues
- Make sure your callback page doesn't redirect away from
localhostbefore running the close/refresh script—keep the final page in the same origin as your main app. - Test browser popup blockers: Ensure your users allow popups from your site, otherwise the auth window won't open at all.
- Double-check that
window.openerisn'tnull(this can happen if the main window was closed while the popup was open—adding the!window.opener.closedcheck handles this edge case).
内容的提问来源于stack exchange,提问作者Dennis

