0
点赞
收藏
分享

微信扫一扫

原生js判断链接是否有效

这很简单,我们可以通过请求的方式确定是否有效。本文通过ajax和jsonp实现。

通过ajax发起http请求会存在跨域问题,因为浏览器存在同源策略。何为跨域?我也不太清楚,以下几个例子可能对你理解跨域有帮助

协议不同、子域名不同、主域名不同、端口不同、一个页面用子域名和一个页面用主域名、一个页面用ip和一个页面用域名;满足以上一个条件即为跨域。

跨域

​​http://localhost.com​​​ https://localhost.com
跨域,协议不同

​​http://test.localhost.com​​​ http://www.localhost.com
跨域,子域名不同

​​http://localhost.com​​​ http://test.com
跨域,主域名不同

​​http://localhost.com:80​​​ http://localhost.com:8080
跨域,端口不同

​​http://localhost.com​​​ http://test.localhost.com
跨域

​​http://localhost.com​​​ http://127.0.0.1.com
跨域

解决跨域的方法有很多,jsonp就是其中之一。原理大概就是利用了浏览器对标签的src属性没有同源限制这一条。

<script src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=百度翻译?cb=DataFun" type="text/javascript" charset="utf-8"></script>

DataFun是接收数据的回调函数

本文中的ajax是判断站内链接,jsonp判断站内外链接(可设置一律使用jsonp判断)

不再废话,上代码

代码

getUrlState.html

<!DOCTYPE html>
<html>
<head>
<title>getUrlState</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/getUrlState.css">
</head>
<body>
<div class="main">
<div class="InformationDiv">
<div class="TitleH3">
<h3>你正在测试链接是否有效</h3>
</div>
<p>
<span>你正在测试的链接地址:</span>
<span>https://baoidu.com</span>
</p>
</div>
<div class="ButtonList">
<button>取消访问</button>
<button>继续访问</button>
</div>
</div>
</body>
<script src="./JavaScript/getUrlState.js"></script>
<script type="text/javascript">
var url = 'http://127.0.0.1';
// url='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=百度翻译'
document.querySelector('p>span:nth-child(2)').innerText = url;
getUrlState({
type: 'get',
url: url,
async:false,
RequestType: 'JsonP',
Timeout: '1000',
State: function(state) {
console.log(state);
if(state.state === 404){
document.querySelectorAll('.ButtonList>button')[1].style.backgroundColor = '#f3f3f3';
document.querySelectorAll('.ButtonList>button')[1].style.borderColor = '#f3f3f3';
document.querySelectorAll('.ButtonList>button')[1].style.color = '#008CD6';
document.querySelectorAll('.ButtonList>button')[1].disabled = 'disabled';
document.querySelector('.TitleH3>h3').innerText = '温馨提示:你正在测试的是无效链接';
}
if(state.state === 200){
document.querySelector('.TitleH3>h3').innerText = '温馨提示:你正在测试的是有效链接';
document.querySelectorAll('.ButtonList>button')[1].onclick=function(){
window.location.replace(url);
}
}
document.querySelectorAll('.ButtonList>button')[0].onclick=function(){
window.close();
}
}
});
</script>
</html>

style.css

* {
margin: 0px;
padding: 0px;
/* 好看的颜色#006d9a */
/* rgb(0,140,214)==#008CD6;来源:ai文件 */
}

ul,
ol,
li {
list-style-type: none;
}

input,
textarea,
button {
outline: none;
}

a {
text-decoration: none;
}

.logo,
.ButtonList,
.Footer,
.LinkList,
.Tips,
.Tips>* {
-moz-user-select: -moz-none;
-moz-user-select: none;
-o-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
/*适用ie*/
-ms-user-select: none;
user-select: none;
}

/* word-break: break-word; */
/* 文本行的任意字内断开 */
/* word-wrap: break-word; */
/* IE */
/* white-space: -moz-pre-wrap; */
/* Mozilla */
/* white-space: -hp-pre-wrap; */
/* HP printers */
/* white-space: -o-pre-wrap; */
/* Opera 7 */
/* white-space: -pre-wrap; */
/* Opera 4-6 */
/* white-space: pre; */
/* CSS2 */
/* white-space: pre-wrap; */
/* CSS 2.1 */
/* white-space: pre-line; */
/* font-size: 21px; */

getUrlState.css

body {
width: 100vw;
height: 100vh;
background-color: #f3f3f3;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}

.main {
width: 337px;
min-width: 147px;
padding: 25px;
border-radius: 5px;
background-color: #FFFFFF;
border: 1.5px solid #008CD6;
}

.ButtonList {
width: 100%;
height: 24px;
display: flex;
align-items: center;
justify-content: flex-end;
}

.ButtonList>button {
height: 100%;
color: #f3f3f3;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
padding: 1px 6px;
border-radius: 3px;
box-sizing: border-box;
border: 1.5px solid #008CD6;
background-color: #008CD6;
}

.ButtonList>button:hover {
background-color: #006d9a;
}

.ButtonList>button+button {
margin-left: 10px;
}

.TitleH3 {
width: 100%;
margin-bottom: 15px;
display: flex;
justify-content: center;
align-items: center;
}

p {
width: 100%;
border-bottom: 1px solid #008CD6;
padding-bottom: 5px;
margin-bottom: 15px;
word-wrap: break-word;
text-align: justify;
}

p>span:nth-child(2) {
text-decoration: none;
color: #008CD6;
word-break: break-all;
}

@media screen and (max-width: 389px) {
.main {
width: calc(90vw - 30px);
height: auto;
padding: 15px;
}
}

getUrlState.js

(function(event) {
// 解决IE(对象不支持“assign”属性或方法)
if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}

target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
// 解决IE(对象不支持“includes”属性或方法)
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
if (typeof start !== 'number') {
start = 0;
}

if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}

function getUrlState(parameter) {
let Default = {
type: 'get',
url: null,
RequestType: 'jsonp',
async: true,
CustomMethod:null,
Timeout: 1000,
State: function(state) {
console.log(state);
}
}
getUrlState.Default = Default;
getUrlState.parameter = parameter;
// parameter
getUrlState.prototype.init(Object.assign({}, Default, parameter));
}
// 初始化
getUrlState.prototype.init = function(parameter) {
parameter.RequestType = parameter.RequestType.trim().toLowerCase() || 'jsonp';
if (parameter.url) {
if (parameter.url.replace(/(\s)/g, "")) {
if (Object.prototype.toString.call(parameter.url) !== '[object String]') {
getUrlState.prototype.error('url属性必须为String类型',parameter);
}else{
function UrlState(parameter) {
this.state = null;
this.data = null;
}
let UrlStateObject = new UrlState();
getUrlState.UrlStateObject = UrlStateObject;
getUrlState.DataFun = function(data) {
UrlStateObject.data = data;
}
}
} else {
getUrlState.prototype.error('url属性必须存在',parameter);
}
} else {
getUrlState.prototype.error('url属性必须存在',parameter);
}

parameter.Timeout = parseInt(parameter.Timeout);
if (!parameter.Timeout || parameter.Timeout === NaN || parameter.Timeout === undefined) {
parameter.Timeout = 1000;
}

if (parameter.Timeout < 0) {
getUrlState.prototype.error('Timeout属性值不能小于零',parameter);
}
if (parameter.async && Object.prototype.toString.call(parameter.async) !== '[object Boolean]') {
getUrlState.prototype.error('async属性必须为Boolean类型',parameter);
}
if (parameter.RequestType) {
if (Object.prototype.toString.call(parameter.RequestType) === '[object String]') {
if (!parameter.RequestType.replace(/(\s)/g, "")) {
getUrlState.prototype.error('RequestType属性必须存在',parameter);
}
} else {
getUrlState.prototype.error('RequestType属性必须为String类型',parameter);
}
} else {
getUrlState.prototype.error('RequestType属性必须存在',parameter);
}
(function WebAgreement(url) {
var check_www = 'w{3}' + '[^\\s]*';
var check_http = '(https|http|ftp|rtsp|mms|tls|tcp|websocket|udp|dns)://' + '[^\\s]*';
var strRegex = check_www + '|' + check_http;
var httpReg = new RegExp(strRegex, 'gi');
if (!url.match(httpReg)) {
if (url.substring(0, 2) !== "./" && url.substring(0, 3) !== "../") {
parameter.url = "./" + parameter.url;
}
getUrlState.prototype.Ajax(parameter);
} else {
parameter.url = url.match(httpReg)[0];
if (parameter.RequestType.toLowerCase() === 'jsonp') {
getUrlState.prototype.EstablishScript(parameter);
} else {
getUrlState.prototype.Ajax(parameter);
}
}
})(parameter.url);
}
// Ajax方式判断
getUrlState.prototype.Ajax = function(parameter) {
var BxzAjax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
parameter.type = parameter.type.trim().toLowerCase() || 'get';
if (parameter.async === 'false' || parameter.async === false) {
parameter.async = false;
} else {
parameter.async = true;
}

BxzAjax.open(parameter.type, parameter.url, parameter.async);
if (parameter.type === 'post') {
BxzAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (parameter.RequestType === 'json' && parameter.type === 'post') {
BxzAjax.setRequestHeader("Content-Type", "application/json");
}
BxzAjax.send(null);
var setTime = setTimeout(function() {
// 取消请求
BxzAjax.abort();
getUrlState.prototype.load('Ajax', 404, parameter, null);
clearTimeout(setTime);
}, (parameter.Timeout) + 1);
if (parameter.async) { //异步
BxzAjax.onreadystatechange = function() {
if (BxzAjax.readyState === 4) {
if (BxzAjax.status === 200) {
clearTimeout(setTime);
if (BxzAjax.response) {
// getUrlState.UrlStateObject.data = JSON.parse(BxzAjax.response);
}
getUrlState.prototype.load('Ajax', 200, parameter, null);
}
}
}
} else {
if (BxzAjax.readyState === 4) {
if (BxzAjax.status === 200) {
clearTimeout(setTime);
if (BxzAjax.response) {
// getUrlState.UrlStateObject.data = JSON.parse(BxzAjax.response);
}
getUrlState.prototype.load('Ajax', 200, parameter, null);
}
}
}
}

// 创建script标签
getUrlState.prototype.EstablishScript = function(parameter) {
try {
var symbol = parameter.url.includes("?") ? "&" : "?";
//创建script标签
var script = document.createElement("script");
script.type = 'text/javascript';
script.charset = 'scriptCharset';
script.async='async';
//填写请求地址,添加要传递的数据,传递一个回调函数
script.src = parameter.url + symbol + "&cb=getUrlState.DataFun";
//这个时候我们需要把准备好的script标签添加到页面 最好是添加到脚本以后
document.body.appendChild(script);
getUrlState.prototype.EstablishIframe(parameter);
getUrlState.prototype.ScriptState(script, parameter);
} catch (error) {
getUrlState.prototype.error('创建script标签时发生错误',parameter);
} //捕获错误,其中error就是new Error() 的实例
}
// script标签状态
// label标签
getUrlState.prototype.ScriptState = function(script, parameter) {
try {
var Time = 0;
var setTime = setTimeout(function() {
Time = (parameter.Timeout) + 1;
clearTimeout(setTime);
}, (parameter.Timeout) + 1);
if (script.readyState && Time <= parameter.Timeout) { //IE
script.onreadystatechange = function() {
if (script.readyState == 'complete' || script.readyState == 'loaded') {
script.onreadystatechange = null;
getUrlState.prototype.load(null, 200, parameter, script);
} else {
getUrlState.prototype.load(null, 404, parameter, script);
}
}
} else if (Time <= parameter.Timeout) { //非IE
script.onload = function() {
getUrlState.prototype.load(null, 200, parameter, script);
}
script.onerror = function(error) {
getUrlState.prototype.load(null, 404, parameter, script);
}
} else {
getUrlState.prototype.load(null, 404, parameter, script);
}
} catch (error) {
getUrlState.prototype.error('获取script标签状态时出现错误',parameter);
} //捕获错误,其中error就是new Error() 的实例
}


getUrlState.prototype.EstablishIframe = function(parameter) {
try {
var iframe = document.createElement("iframe");
iframe.width = 0;
iframe.height = 0;
iframe.style.display = 'none';
iframe.frameborder = 'on';
iframe.src = parameter.url;
document.body.appendChild(iframe);
} catch (error) {
getUrlState.prototype.error('获取Iframe标签状态时出现错误',parameter);
} //捕获错误,其中error就是new Error() 的实例
}

// <iframe src="" width="" height=""></iframe>

// 完成
getUrlState.prototype.load = function(who, State, parameter, script) {
if (parameter.CustomMethod && Object.prototype.toString.call(parameter.CustomMethod) === '[object Function]') {
getUrlState.UrlStateObject['state'] = State;
parameter.CustomMethod(getUrlState.UrlStateObject);
}else{
if (parameter.State && Object.prototype.toString.call(parameter.State) === '[object Function]') {
getUrlState.UrlStateObject['state'] = State;
console.log(getUrlState.UrlStateObject)
parameter.State(getUrlState.UrlStateObject);
}
}
if (who !== 'Ajax' && who !== 'error') {
document.body.removeChild(script);
}
}
// 代码或操作出错
getUrlState.prototype.error = function(error,parameter) {
getUrlState.prototype.load('error', 404, parameter, null);
throw Error(error);
}
event.getUrlState = getUrlState;
})(window);

举报

相关推荐

0 条评论