桌面/手機瀏覽器正常,放入微信公眾號後 window.location.href = 'https://other.com' 無反應,且前置代碼用了 window.opener 獲取信息。
location.href 跨域跳轉有白名單限制,非業務域名會被攔截。window.open,因此無 opener 引用。wx.openLocation(僅地理位置)不適用於一般網頁跳轉。
// 前端跳轉到自家後端
window.location.href = 'https://myapi.com/redirect?target=' + encodeURIComponent(targetUrl);
// 後端 Controller
@GetMapping("/redirect")
public void redirect(@RequestParam String target, HttpServletResponse resp) throws IOException {
// 校驗 target 域名白名單,防開放重定向漏洞
if (isAllowedDomain(target)) {
resp.sendRedirect(target);
} else {
resp.sendError(400, "非法跳轉目標");
}
}
優點:繞過微信前端攔截,可攜帶參數,安全可控。
若原意是獲取用戶身份,應使用標準 OAuth2 流程:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=...&redirect_uri=...&scope=snsapi_userinfocode,換取 access_token + openid<web-view src="https://other.com" bindmessage="onMessage"></web-view>
// 小程序端可通過 postMessage 與網頁通信
window.opener 獲取父頁面數據,改用 URL 參數或 Session 傳遞。X-Frame-Options: ALLOW-FROM 且在微信白名單內。