客服系统前端开发:JavaScript获取URL中的协议部分和域名部分【唯一客服】网页在线客服系统

再客服系统中如果想要链接websocket需要确定是ws://  还是wss:// 所以,我封装了两个函数,用于获取URL中的协议是HTTP 还是HTTPS ,以及获取到域名部分

可以使用 JavaScript 中的 String.prototype.match() 方法来执行匹配操作,并使用第一个捕获组来获取匹配的域名部分。

复制代码
//获取协议部分
function getProtocolFromUrl(url) {
    if(url==""){
        url=window.location.href;
    }
    const regex = /^(https?)/i;
    const match = url.match(regex);
    return match[1];
}
console.log(getProtocolFromUrl("https://gofly.v1kf.com")); // "https"
console.log(getProtocolFromUrl("http://gofly.v1kf.com/")); // "http"
console.log(getProtocolFromUrl("http://gofly.v1kf.com")); // "http"
console.log(getProtocolFromUrl("http://www.baidu.com/sdsdsds")); // "http"
复制代码

这样就能判断是使用ws还是wss去链接websocket

还要获取域名部分

复制代码
//获取域名部分
function getDomainFromUrl(url) {
    if(url==""){
        url=window.location.href;
    }
    const regex = /^https?:\/\/([^\/]+)/i;
    const match = url.match(regex);
    return match[1];
}
console.log(getDomainFromUrl("")); // 当前页面的域名
console.log(getDomainFromUrl("https://gofly.v1kf.com")); // "gofly.v1kf.com"
console.log(getDomainFromUrl("http://gofly.v1kf.com/")); // "gofly.v1kf.com"
console.log(getDomainFromUrl("http://gofly.v1kf.com")); // "gofly.v1kf.com"
console.log(getDomainFromUrl("http://www.baidu.com/sdsdsds")); // "www.baidu.com"
复制代码

实际项目中的使用

 

 

唯一在线客服系统

https://gofly.v1kf.com

 

posted @   唯一客服系统开发笔记  阅读(269)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-01-08 [uniapp] GOFLY在线客服系统- uniapp增加播放背景音效或者按钮音效
2021-01-08 [javascript] ie下audio不支持一些媒体类型
2021-01-08 [javascript] ie下不支持incudes属性和方法
2021-01-08 [MySQL] 数据库自增ID用完了会怎么样
2020-01-08 [Linux] git add时的注意事项
点击右上角即可分享
微信分享提示
1
chat with us