Greasy Fork

显示Steam在线人数

在最近评测上增加在线人数文本, 观察游戏的实际热度

目前为 2023-10-15 提交的版本。查看 最新版本

// ==UserScript==
// @name         显示Steam在线人数
// @description  在最近评测上增加在线人数文本, 观察游戏的实际热度
// @version      1.0
// @author       cweijan
// @namespace    cweijan/steam_online_players
// @license      MIT
// @run-at       document-start
// @grant        GM_xmlhttpRequest
// @include      *store.steampowered.com/app/*
// ==/UserScript==

function makeElement(htmlString) {
	var div = document.createElement('div');
	div.innerHTML = htmlString.trim();
	return div.firstChild;
}


let onlineTextNode;
let initText = GM_xmlhttpRequest ? '数据加载中' : '无网络权限!'
const appId = location.href.match(/app\/(\d+)/)?.[1];

function fillText(msg) {
	if (onlineTextNode) onlineTextNode.textContent = msg
	else initText = msg
}

if (GM_xmlhttpRequest) {
	GM_xmlhttpRequest({
		method: "GET",
		url: `https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?appid=${appId}`,
		onload(response) {
			try {
				const playerCount = JSON.parse(response.responseText).response.player_count;
				fillText(playerCount)
			} catch (error) {
				fillText(`解析API返回值失败:${response.responseText}`)
			}
		},
		onerror(response) {
			console.log(response)
			fillText("请求失败")
		}
	})
}

const observer = new MutationObserver(mutationList => {
	for (var mutation of mutationList) {
		for (var node of mutation.addedNodes) {
			if (!node.querySelectorAll) continue;
			if (node.getAttribute("id") == 'userReviews') {
				const html = `<div class="user_reviews_summary_row">
								<div class="subtitle column">在线人数:</div>
								<div class="summary column">
									<span id="onlinePlayers" style="color: #5ac985;">${initText}</span>
								</div>
							</div>`
				node.insertBefore(makeElement(html), node.firstChild)
				onlineTextNode = document.getElementById('onlinePlayers')
			}
		}
	}
});

observer.observe(document, { childList: true, subtree: true });