从 Javascript 中的脚本标签中提取 HTML 页面变量

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

如何从 Javasc./Typescript 中返回的 HTML 页面中的页面脚本标记中提取变量?

我对服务器的 API 请求:

const response = await fetch( ... )

响应包含一个大的 HTML 页面,这里只是一个例子:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Steam App Daten</title>
</head>
<body>

    <h1>Willkommen auf der Seite für Steam App Daten</h1>

    <script type="text/javascript">
        var g_rgAppContextData = {
            "730": {
                "appid": 730,
                "name": "Counter-Strike 2",
                "icon": "https://cdn.fastly.steamstatic.com/steamcommunity/public/images/apps/730/8dbc71957312bbd3baea65848b545be9eae2a355.jpg",
                "link": "https://steamcommunity.com/app/730"
            }
        };
        var g_rgCurrency = [];
    </script>

</body>
</html>

我只想提取变量g_rgAppContextData,没有其他任何东西。我知道,我可以使用 getElementsByTagName("script") 选择脚本标签,但是如果有 2 个脚本标签怎么办?以及如何仅选择变量?

javascript html dom
1个回答
0
投票

在示例中,我尝试在三个不同的位置获取全局变量。如果你看看事情的顺序,变量是在 HTML 文档中声明之后定义的——这是有道理的。

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Steam App Daten</title>
    <script type="text/javascript">
      console.log('In head:', typeof g_rgAppContextData != 'undefined' ? 'defined':'not defined');
    </script>
</head>
<body>
    <script type="text/javascript">
      console.log('After body:', typeof g_rgAppContextData != 'undefined' ? 'defined':'not defined');
    </script>
    <h1>Willkommen auf der Seite für Steam App Daten</h1>
    <script type="text/javascript">
        var g_rgAppContextData = {
            "730": {
                "appid": 730,
                "name": "Counter-Strike 2",
                "icon": "https://cdn.fastly.steamstatic.com/steamcommunity/public/images/apps/730/8dbc71957312bbd3baea65848b545be9eae2a355.jpg",
                "link": "https://steamcommunity.com/app/730"
            }
        };
        var g_rgCurrency = [];
    </script>
    <script type="text/javascript">
      console.log('In the end:', typeof g_rgAppContextData != 'undefined' ? 'defined':'not defined');
    </script>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.