如何用JavaScript获取网页标题且规避CORS限制?
Obsidian短链接扩展插件的CORS问题与网页标题获取困境
我正在开发一款Obsidian插件,用于将Markdown中的短链接(如bit.ly、t.co等)扩展为带描述性标题的标准Markdown链接格式[标题](网页链接)。核心需求是读取目标网页的标题,但持续遭遇CORS问题,无法正常获取标题。
我尝试过CORS代理方案,但免费代理要么不稳定、不安全,要么仅作演示用途,无法投入实际使用。
获取网页标题的具体代码如下:
// Helper function to get the title of a web page export async function getTitle(url:string){ try { const request = new Request(url, { method: 'GET', mode: 'cors', headers: { 'Content-Type': 'text/html' } }); const response = await fetch(request); const html = await response.text(); let title = ''; const titleMatches:string[] = html.match(/<title.*?>.*?<\/title>/gmi)||[]; if (titleMatches.length > 0) { title = titleMatches[0]; console.log(title); } if (title.search(/<title/gi) !== -1){ const titleText = title.substring(title.indexOf('>')+1); const res = titleText.replace('</title>',''); console.log(res); return res; } return ''; } catch (err) { console.error(`Failed to retrieve title with error: ${err}`); return ''; } }
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

