MediaWiki:Common.js:修订间差异
MediaWiki界面页面
更多操作
无编辑摘要 |
无编辑摘要 |
||
| 第22行: | 第22行: | ||
//页面摘要功能 | //页面摘要功能 | ||
function | function fillPageCards() { | ||
document.querySelectorAll('.page- | document.querySelectorAll('.page-card').forEach(card => { | ||
const title = card.dataset.title; | |||
const title = | if (!title || card.dataset.filled) return; | ||
const | const excerptDiv = card.querySelector('.page-excerpt'); | ||
const imgTag = card.querySelector('.page-card-image img'); | |||
fetch( | // 1️⃣ 获取摘要 | ||
const excerptUrl = '/api.php?action=query&prop=extracts&exchars=200&titles=' + | |||
encodeURIComponent(title) + '&format=json'; | |||
fetch(excerptUrl) | |||
.then(resp => resp.json()) | .then(resp => resp.json()) | ||
.then(data => { | .then(data => { | ||
| 第43行: | 第45行: | ||
} | } | ||
const temp = document.createElement('div'); | const temp = document.createElement('div'); | ||
temp.innerHTML = html; | temp.innerHTML = html; | ||
// | // 保留 <a>,删除其他标签 | ||
temp.querySelectorAll('*').forEach(node => { | |||
if (node.tagName !== 'A') { | if (node.tagName !== 'A') { | ||
node.replaceWith(document.createTextNode(node.textContent)); | |||
} | } | ||
}); | }); | ||
let textWithLinks = temp.innerHTML.replace(/[\r\n]+/g, ' '); | let textWithLinks = temp.innerHTML.replace(/[\r\n]+/g, ' '); | ||
excerptDiv.innerHTML = textWithLinks; | |||
}) | |||
.catch(err => console.error('Failed to fetch excerpt:', title, err)); | |||
// 2️⃣ 获取第一张图片 | |||
const imageUrl = '/api.php?action=query&titles=' + encodeURIComponent(title) + | |||
'&prop=images&format=json'; | |||
fetch(imageUrl) | |||
.then(resp => resp.json()) | |||
.then(data => { | |||
const pages = data.query.pages; | |||
for (let pageId in pages) { | |||
if (pages.hasOwnProperty(pageId)) { | |||
const images = pages[pageId].images || []; | |||
if (images.length > 0) { | |||
const firstImageTitle = images[0].title; // "File:xxx.jpg" | |||
// 获取图片实际 URL | |||
const imageInfoUrl = '/api.php?action=query&titles=' + | |||
encodeURIComponent(firstImageTitle) + | |||
'&prop=imageinfo&iiprop=url&format=json'; | |||
fetch(imageInfoUrl) | |||
.then(resp => resp.json()) | |||
.then(imgData => { | |||
const imgPages = imgData.query.pages; | |||
for (let imgId in imgPages) { | |||
if (imgPages.hasOwnProperty(imgId)) { | |||
const url = imgPages[imgId].imageinfo?.[0]?.url; | |||
if (url) imgTag.src = url; | |||
} | |||
} | |||
}); | |||
} | |||
break; | |||
} | |||
} | |||
}) | }) | ||
.catch(err => | .catch(err => console.error('Failed to fetch image:', title, err)); | ||
card.dataset.filled = '1'; | |||
}); | }); | ||
} | } | ||
// | // 立即执行 | ||
fillPageCards(); | |||
// 可选:监听后续 DOM 变化 | // 可选:监听后续 DOM 变化 | ||
const observer = new MutationObserver( | const observer = new MutationObserver(fillPageCards); | ||
observer.observe(document.body, { childList: true, subtree: true }); | observer.observe(document.body, { childList: true, subtree: true }); | ||