通过小部件设置第三方cookie,这样我以后就可以识别用户了

Setting a 3rd party cookie through a widget so I can recognize the user later

本文关键字:就可以 识别 用户 小部 设置 第三方 cookie      更新时间:2023-09-26

我正试图从用户添加到其网站的小部件中设置第三方cookie。这个小部件在user-site.com上,托管代码是o admin-site.com。我的目标是为他们设置一个cookie,这样小部件就能在安装小部件的任何网站上识别他们。我不想使用弹出窗口让他们通过我的网站登录。我只想通过小部件为他们设置一个cookie,然后能够识别他们。

  • 需要2行代码才能使小部件出现;一个.js文件和一行html

将小部件添加到user-site.com后,将显示两个文本字段;1个代表您的姓名,1个代表电子邮件。然后单击按钮提交。然后,我为用户返回一个user_id,并尝试通过小部件设置一个cookie。这不起作用。。。

user-site.com需要在其html中添加2行代码才能显示小部件

<script src="http://example.com/widget.js" type="text/javascript" async="true"></script>
<div id="widget-container" class="8AORPIY0"></div>

小工具.js

// Create the input fields and submit button
var login_name = '<input type="text" name="name" />';
var login_email = '<input type="email" name="email" />';
var login_button = '<input type="button" value="Login" />';
var add_fields_to_html_snippet = login_name + login_email + login_button;
$('#widget-container').html(add_fields_to_html_snippet);
$.ajax({
    url : "http://example.com/widget_update.php",
    type: "GET",
    data: { name:name, email:email },
    dataType:"jsonp",
    jsonp:"mycallbackupdate",
    success:function(data) { // The server side sends back the users id which will become the value of the 3rd party cookie
        // This is the value *user_id returned from server side
        var value = data.user_id;
        // I'm trying to set a cookie but it doesn't work
        document.cookie = 'cookie1=' + user_id + '; expires=Fri, 3 Aug 2016 20:47:11 UTC; path=/'
        }           
    });

如何通过嵌入式小部件为用户成功设置cookie?我希望能够识别来自任何使用此小部件的网站的用户。

更新

我还尝试过从服务器端设置cookie:

$_COOKIE['user_id'] = $user_id;
$expire = time() + 60 * 60 * 24 * 365;
setcookie('cookie1', $_COOKIE['user_id'], $expire);

但是,我无法从widget.js中获取cookie1的值

alert(document.cookie.indexOf("cookie1")); // This doesn't return the same value I set the cookie to from the HTTP header

但是,返回的值与我在HTTP头中设置cookie的值不同。如何在widget.js中调用相同的值?

JavaScript始终在嵌入的HTML文档的上下文中运行,因此您无法使用JavaScript设置第三方cookie。

在JSONP响应上使用HTTP头设置cookie(请记住,许多浏览器都被配置为完全阻止第三方cookie)。

widget_update.php设置cookie。

您应该设置";"安全";属性(假设admin-site.com通过HTTPS提供服务),以防止最终用户在公共WiFi上时窃取该信息。

您还需要将SameSite属性设置为";无";。现代浏览器正在努力提高互联网安全性,防止数据泄露,因此如果你没有明确表示允许在第三方网站上使用"cookie",cookie可能会被屏蔽;samesite=none";。

相关文章: