
如何在 iframe 中引入短链并展示对应内容?
使用 iframe 来嵌入其他页面时,若遇到的页面地址是短链接,iframe 会因无法自动重定向而无法展示。以下两种方式可以解决这个问题:
方法一:获取长链后赋值
const shortUrl = 'http://shorturl.com/abcd';
// 获取长链
fetch(shortUrl)
.then((res) => res.url)
.then((longUrl) => {
// 赋值给 iframe 的 src
const iframe = document.querySelector('iframe');
iframe.src = longUrl;
});方法二:自定义拦截
如果无法获取或修改短链接,可以自定义一个拦截器来对 iframe 的请求进行修改。
// 拦截 fetch 请求
const originalFetch = window.fetch;
window.fetch = (url, ...args) => {
// 检查是否为短链接
if (isShortLink(url)) {
// 获取长链接
return fetch(getLongLink(url), ...args);
}
// 其他请求照常处理
return originalFetch(url, ...args);
};通过这两种方式,可以实现 iframe 引入短链并正确展示相应内容。
以上就是如何使用 iframe 引入短链并展示对应内容?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号