如何使用Javascript从缩短的URL中获取域名? [英] How to get domain name from shortened URL with Javascript?
问题描述
假设我有一个要使用前端技术阻止的域的列表.我想阻止域托管的任何URL.我头顶上有以下方法:
Suppose I have a list of domains that I want to block with front end technology. I want to block any URL that is hosted by the domain. On top of my head I have the following methods:
- regex
-
string.split("/")
-
location.hostname
但是,如果URL是一个简短的URL,该怎么办?例如 https://goo.gl/lWyZ5B
.以上所有方法都会返回不想要的结果: goo.gl
.
But what if the URL is a shortened one? e.g. https://goo.gl/lWyZ5B
. All of the above methods will return undesired result: goo.gl
.
这实际上是我计划的Chrome扩展程序的一部分.因此,如果结果在阻止列表中,也许Chrome可以获取缩短的URL,然后重定向到警告页面?
This is actually a part of a Chrome extension I am planning. So maybe Chrome can fetch the shortened URL then redirect to a warning page if the result is on block list?
推荐答案
了解缩短的URL背后的真实主机的唯一方法是实际尝试获取URL,然后查看是否获得302重定向并查看该重定向URL是什么.
The only way to know what the real host that is behind a shortened URL is to actually attempt to fetch the URL and then see if you get a 302 redirect and see what that redirect URL is.
由于通常无法从浏览器Javascript中加载跨域URL,因此可能需要服务器来为您执行此操作并将结果返回给您.
Since you generally can't load cross-origin URLs from within browser Javascript, you would probably need a server to do this for you and return the result to you.
另一种选择是,如果链接缩短器是您有权访问API的已知链接,则可以查询该API以查看给定的缩短链接是针对其的快捷方式.例如,bit.ly具有此api http://dev.bitly.com/data_apis.html.该API通常会允许跨源访问,因此您可以从浏览器访问它.
One other option is that if the link shortener is a known one that you have API access to, then you can query that API to see what a given shortened link is a shortcut for. For example, bit.ly has this api http://dev.bitly.com/data_apis.html. The API will typically allow cross origin access so you can access it from a browser.
由于您不能自信地访问所有可能的链接缩短器,因此该策略实际上仅适用于您准备的特定链接缩短器.对于任何缩短链接的通用解决方案,都需要使用服务器直接访问URL以获得重定向.
Since you can't confidently have API access to all possible link shorteners, this strategy is really only applicable to specific link shorteners that you prepare for. A general solution for any link shortener would need to use a server to access the URL directly to get the redirect.
例如,这是一个简单的node.js程序,该程序获取一个URL,并检查是否返回了重定向响应,如果是,则获取重定向URL.
For example, here's a simple node.js program that fetches a URL and checks to see if it returns a redirect response and gets the redirect URL if so.
var request = require("request");
request({url: "https://goo.gl/lWyZ5B", followRedirect: false}, function(error, response, body) {
console.log(response.statusCode);
if (response.statusCode >= 300 && response.statusCode < 400) {
console.log(response.headers.location);
}
});
这将产生以下输出:
301
https://www.youtube.com/watch?v=ZrU_tt4R3xY
这可以包装在将URL作为请求并返回结果URL的服务器中.
This could be wrapped in a server that would take a URL as a request and return the resulting URL.
这篇关于如何使用Javascript从缩短的URL中获取域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!