首页 > 解决方案 > 从缩短的链接中检索原始 URL

问题描述

我想在单击它并访问目的地之前从缩短的链接中检索原始 URL。

我有这个外部链接https://example.com/api.php?redirect=XXXXXXX重定向到https://new.com。如何使用 PHP 或 Javascript获取原始链接https://new.com 。

标签: javascriptphphtmlurlredirect

解决方案


const extractParams = (url) =>{
    const search = url.split("?")[1];
    return Object.fromEntries(
        search.split("&").map(param => param.split("="))
    )
}

window.addEventListener("load", ()=>{
    // select all a tag containg word redirect in href attr
    const links = document.querySelectorAll('a[href*="redirect"]')
    links.forEach(el => {
       el.addEventListener("click", (e) =>{
       /// remove line below in your solution if you need to links works correctly
            e.preventDefault();
            const url = e.target.href;
            const params = extractParams(url);
            //belove you have access to redirect and any otter url params
            console.log(params.redirect);
       })
    })
})
<a href="https://example.com/api.php?redirect=https://new.com">New</a>
<a href="https://example.com/api.php?redirect=https://ben.com">Ben</a>
<a href="https://example.com/api.php?redirect=https://den.com">Den</a>


推荐阅读