fix: replace weread:// deep link with web URL for 'Open in WeRead' button

The hardcoded 'weread://reading?bId=...' scheme only works on mobile
devices with the WeRead app installed. On desktop browsers, clicking
the button did nothing. Now uses data.deep_link from the API response
(https://weread.qq.com/...) with fallback logic: try weread:// scheme
via hidden iframe for 1.5s, then fall back to opening the web URL.
This commit is contained in:
admin committed 2026-07-17 12:14:12 +08:00
1 parent 4c916eceb7
commit d276608538
1 file changed
+39 -1
+39 -1
View File
@@ -155,6 +155,44 @@ function scrollToTop() {
window.scrollTo({ top: 0, behavior: "smooth" }); window.scrollTo({ top: 0, behavior: "smooth" });
} }
/**
* 在微信读书中打开书籍。
* 优先使用 API 返回的 deep_link(https://weread.qq.com/... 网页链接),
* 没有则用 book_id 构造网页链接。先尝试 weread:// 深链接唤起 App,
* 1.5 秒后无响应则回退到网页版。
*/
function openInWeRead(bookId, deepLink) {
const webUrl = deepLink || `https://weread.qq.com/#book/${bookId}`;
const schemeUrl = `weread://reading?bId=${bookId}`;
// 尝试唤起 App(移动端),同时设置定时器回退到网页版
let triggered = false;
const fallbackTimer = setTimeout(() => {
if (!triggered) window.open(webUrl, "_blank");
}, 1500);
// 监听页面可见性变化(App 唤起成功会切到后台)
const onVisChange = () => {
if (document.hidden) {
triggered = true;
clearTimeout(fallbackTimer);
}
};
document.addEventListener("visibilitychange", onVisChange);
// 尝试打开深链接
const iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = schemeUrl;
document.body.appendChild(iframe);
setTimeout(() => document.body.removeChild(iframe), 2000);
// 桌面端不会有 visibilitychange,确保 fallback 一定执行
setTimeout(() => {
document.removeEventListener("visibilitychange", onVisChange);
}, 3000);
}
// ===== 全局搜索(顶部常驻搜索框) ===== // ===== 全局搜索(顶部常驻搜索框) =====
function globalSearch() { function globalSearch() {
@@ -728,7 +766,7 @@ function openBook(bookId) {
${data.word_count ? `<div class="detail-info-item"><strong>字数:</strong> ${(data.word_count / 10000).toFixed(1)}万字</div>` : ''} ${data.word_count ? `<div class="detail-info-item"><strong>字数:</strong> ${(data.word_count / 10000).toFixed(1)}万字</div>` : ''}
</div> </div>
<div class="detail-actions"> <div class="detail-actions">
<button class="btn-primary" onclick="window.open('weread://reading?bId=${bookId}','_blank')">在微信读书中打开</button> <button class="btn-primary" onclick="openInWeRead('${bookId}', ${data.deep_link ? `'${data.deep_link}'` : 'null'})">在微信读书中打开</button>
<button class="btn-primary detail-action-thoughts" onclick="closeModal('bookDetailModal');openThoughtsPage('${bookId}', '${(data.title || '').replace(/'/g, "\\'")}', '${(data.author || '').replace(/'/g, "\\'")}', '${data.cover || ''}')">📖 查看想法</button> <button class="btn-primary detail-action-thoughts" onclick="closeModal('bookDetailModal');openThoughtsPage('${bookId}', '${(data.title || '').replace(/'/g, "\\'")}', '${(data.author || '').replace(/'/g, "\\'")}', '${data.cover || ''}')">📖 查看想法</button>
</div> </div>
`; `;