2023 年 2 月 28 日更新:不再采用下面不太安全的新增评论表单方式获取 windows11,之前方法会点审查元素的人都能直接修改表单伪造成 windows11 系统(虽然这些信息想隐藏的人是可以任意伪造的),现在直接改到纯后端获取,直接使用 php 函数:
今天何先生在查看网站有什么 bug 时,发现当用户是 windows11 系统评论,何先生网站评论区显示的操作系统依旧是 windows10,于是上微软官网查了一番,官网是这样说的:
不会更新 User-Agent 字符串来区分 Windows 11 和 Windows 10。 建议不要使用 User-Agent 字符串来检索用户代理数据。 不支持 User-Agent 客户端提示的浏览器将无法区分 Windows 11 和 Windows 10。
引言来源地址:https://learn.microsoft.com/zh-cn/microsoft-edge/web-platform/how-to-detect-win11
这就尴尬了,何先生写的评论区显示浏览器和操作系统等信息就是用用户 User-Agent 来实现的,你这不更新 User-Agent,让我如何是好呢?你这难道是因为 Windows11 是在 Windows10 的基础上换了个皮而已,然后不好意思说吗?
微软官网提供了一个 JavaScript 代码用来识别 Windows11:
navigator.userAgentData.getHighEntropyValues(["platformVersion"])
.then(ua => {
if (navigator.userAgentData.platform === "Windows") {
const majorPlatformVersion = parseInt(ua.platformVersion.split('.')[0]);
if (majorPlatformVersion >= 13) {
console.log("Windows 11 or later");
}
else if (majorPlatformVersion > 0) {
console.log("Windows 10");
}
else {
console.log("Before Windows 10");
}
}
else {
console.log("Not running on Windows");
}
});
于是何先生在网上搜索了一番,找到一篇文章有了个大概思路,但是作者没有写明具体操作方法,我这边就将我的实现方法放上来,方便小白朋友。
非常简单,仅需三步,即可支持显示 Windows11 系统信息。继续往下看。
第一步:
在你的评论 js 页面放入以下代码:
//判断 windows11
function is_win11() {
if (navigator.userAgentData != undefined) {
if (navigator.userAgentData.getHighEntropyValues != undefined) {
navigator.userAgentData.getHighEntropyValues(["platformVersion"]).then(ua => {
if (navigator.userAgentData.platform === "Windows") {
const majorPlatformVersion = parseInt(ua.platformVersion.split('.')[0]);
if (majorPlatformVersion >= 13) {
const ul = document.querySelector('.dropdown-menu.box-body ul');
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'os_type';
input.value = 'win11';
ul.appendChild(input);
}
}
});
}
}
}
is_win11();//调用函数
第二步:
然后在你的 function.php 页面放入以下代码:
function modify_user_agent_on_comment( $commentdata ) {
if ( ( isset( $_POST['os_type'] ) ) && ( $_POST['os_type'] != '') ) {
$commentdata['comment_agent'] = str_replace( 'Windows NT 10.0', 'Windows NT 11.0', $_SERVER['HTTP_USER_AGENT'] );
}
return $commentdata;
}
add_filter( 'preprocess_comment', 'modify_user_agent_on_comment' );
第三步:
第三步何先生就没法直接说明了,因为每个人写的代码不一样,我只做简单介绍:
你只需要根据你的获取操作系统的代码依葫芦画瓢,用正则表达式获取 User-Agent 中 Windows NT 11.0 的字符串来判断是 Windows11 即可。
最后再次声明,免得大家误解,Windows NT 11.0 是咱们通过上面代码进行修改的,微软官方并没有 NT 11.0 这个内核,Windows11 的内核和 Windows10 的内核是一样的,都是 NT 10.0。
JS 版本参考链接:https://www.lovestu.com/wordpressrhsbwindows11pl.html
- 最新
- 最热
只看作者