You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证浏览器扩展用户是否已登录(关联网站Session)

扩展Popup检测网站Session的实现方案

1. 先在网站端做Session验证接口

在你的服务器上新建check_session.php,用来返回当前用户的Session状态:

<?php
session_start();
// 检查名为'users'的Session是否存在
echo json_encode([
    'logged_in' => isset($_SESSION['users'])
]);
exit;
?>

2. 配置扩展的跨域权限

修改扩展的manifest.json,添加目标网站的访问权限(以Manifest V3为例):

{
  "manifest_version": 3,
  "name": "你的扩展名称",
  "version": "1.0",
  "permissions": ["activeTab"],
  "host_permissions": ["https://你的网站域名/*"], // 替换成实际网站域名
  "action": {
    "default_popup": "popup.html"
  }
}

要是用Manifest V2,直接把host_permissions的内容放到permissions数组里就行。

3. Popup.html的检测逻辑

在popup里通过请求验证接口判断Session状态,决定显示内容还是跳转:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script>
        // 发送请求检查Session
        fetch('https://你的网站域名/check_session.php', {
            credentials: 'include' // 必须加,携带Session对应的Cookie
        })
        .then(res => res.json())
        .then(data => {
            if (data.logged_in) {
                // Session存在,显示正常内容
                document.getElementById("main-content").style.display = "block";
            } else {
                // 无Session,跳转到错误页
                window.location.href = "error.html";
            }
        })
        .catch(() => {
            // 请求失败也跳错误页
            window.location.href = "error.html";
        });
    </script>
</head>
<body>
    <div id="main-content" style="display: none;">
        <!-- 这里放Popup的正常内容 -->
        登录成功,欢迎使用!
    </div>
</body>
</html>

4. Error.html的实现

错误页要引导用户登录,还要支持重新验证Session:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script>
        function recheckSession() {
            fetch('https://你的网站域名/check_session.php', {
                credentials: 'include'
            })
            .then(res => res.json())
            .then(data => {
                if (data.logged_in) {
                    // 已登录,返回Popup
                    window.location.href = "popup.html";
                } else {
                    alert("还没登录哦,请先完成登录");
                }
            });
        }
    </script>
</head>
<body>
    <p>你还没登录,请先<a href="https://example.com/login" target="_blank">前往登录</a></p>
    <button onclick="recheckSession()">已登录?点击重新验证</button>
</body>
</html>

核心注意事项

  • credentials: 'include'是关键:PHP的Session依赖PHPSESSID Cookie,这个配置会让请求携带网站的Cookie,服务器才能识别当前用户的Session。
  • 必须配置跨域权限:扩展默认不能跨域请求外部网站,一定要在manifest里声明目标域名的权限,否则请求会被浏览器拦截。
  • Session有效期:确保网站的Session有效期设置合理,避免用户刚登录就被判定为未登录。

内容的提问来源于stack exchange,提问作者pinocchi's dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:07:33