瀏覽器禁止 JavaScript 跨域讀取任意 URL 的 HTML 內容。若目標頁面未設置 Access-Control-Allow-Origin,AJAX 請求會被攔截。
| 方案 | 適用場景 | 實現難度 |
|---|---|---|
| 後端代理 | 任意網站、生產環境 | 中等 |
| 瀏覽器擴展 | 特定網站、用戶安裝 | 中等 |
| iframe + postMessage | 目標頁面合作配置 | 高 |
| 服務端渲染 (SSR) | 自有業務系統 | 低 |
// server.js
app.get('/api/fetch-largest-image', async (req, res) => {
const { url } = req.query;
const html = await fetch(url).then(r => r.text());
const $ = cheerio.load(html);
let maxArea = 0, maxSrc = '';
$('img').each((i, el) => {
const w = $(el).width() || 0;
const h = $(el).height() || 0;
if (w * h > maxArea) {
maxArea = w * h;
maxSrc = $(el).attr('src');
}
});
res.json({ url: maxSrc });
});
$.get('/api/fetch-largest-image', { url: targetUrl }, data => {
console.log('最大圖片:', data.url);
});
純前端 jQuery 無法 突破同源策略獲取任意 URL 內容,必須通過後端代理或合作方配置實現。