如何在进入前 ping 一个网站以查看其是否有效?

问题描述 投票:0回答:1

所以我只是制作一个基本的 html 页面来在 roblox 域中查找随机子站点(?)。当尝试获取该网站时,它会显示重定向错误,即使手动加载它不会显示重定向错误。所以现在我想尝试自动打开带有插入代码或其他内容的网站,然后如果它实际上是一个正在运行的子网站则将其关闭(?)

这是我目前拥有的js代码(全部)

const connect = document.getElementById("connection");
var idsel = document.getElementById("gameid");


function findRandom()
{
    let sel = Math.round(Math.random()*99999999);
    let url = "https://www.roblox.com/games/"+sel+"/";
    connect.setAttribute("href",url);
    idsel.textContent = "Game: "+url;
    

}   

但有时它会加载到

https://www.roblox.com/request-error?code=404
,因为游戏不存在。因此,我不想每次都重新加载,直到它成为一个实际运行的游戏,而是尝试在加载后检查 url 或事先 ping 它,重复直到它成为一个工作 url。我还想通过检查 url 或 ping 来删除特定游戏。

javascript url ping roblox
1个回答
0
投票

您可以使用 JavaScript 中内置的 fetch api。发出获取请求,如果游戏不存在,则会抛出错误,您可以根据需要继续或处理错误。如果该页面存在,则可以设置属性和文本内容。如果您正在寻找此代码,请告诉我:

const connect = document.getElementById("connection");
const idsel = document.getElementById("gameid");

function findRandom() {
    let sel = Math.round(Math.random() * 99999999);
    let url = `https://www.roblox.com/games/${sel}/`;

    fetch(url)
        .then(response => {
            if (!response.ok) {
                // Handle non-existent games or other errors
                throw new Error("Failed to fetch game");
            }
            return response.text();
        })
        .then(text => {
            // Check if the response indicates a valid game
            if (text.includes("The page you requested cannot be found")) {
                // Retry with a new random ID
                findRandom();
            } else {
                // Display the valid game URL
                connect.setAttribute("href", url);
                idsel.textContent = "Game: " + url;
            }
        })
        .catch(error => {
            // Handle fetch errors
            console.error("Error fetching game:", error);
            // Retry with a new random ID
            findRandom();
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.