这是我的解决方案。它使用 javascript 检查选项卡/窗口的唯一 ID 是否存在,并使用 sessionStorage 来存储该唯一 ID。如果用户使用不使用 sessionStorage 的旧浏览器,我还没有测试我的应用程序是否仍然有效——这目前在 Firefox、Safari 和 Chrome 中有效。
我的 index.php 的业务端。一旦完成了一些基本的环境配置(这是 WIKINDX_URL_BASE 等的来源),javascript 是第二个运行的东西:
/**
* Generate/return the unique browser tab/window identifier
*/
$script = WIKINDX_URL_BASE . '/gatekeeper.js?ver=' . WIKINDX_PUBLIC_VERSION;
$qs = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : FALSE;
$url = WIKINDX_URL_BASE . '/index.php' . $qs;
if (!array_key_exists('browserTabID', $_GET)) {
// go into gatekeeper for a redirect and addition of a browserTabID to the querystring
print <<< END
<script src="$script"></script>
<script>redirectSet("$url", "$qs")</script>
END;
}
else {
// go into gatekeeper to check if browserTabID is unique to the tab (perhaps user has `opened link with browserTabID in a new tab/window)`
$id = $_GET['browserTabID'];
print <<< END
<script src="$script"></script>
<script>getBrowserTabID("$url", "$qs", "$id")</script>
END;
}
还有我的 gateway.js:
// gatekeeper.js
/**
* No browserTabID yet set so generate one and redirect
*/
function redirectSet(url, qs)
{
var browserTabID;
if ((sessionStorage.getItem('browserTabID') == null) || !sessionStorage.getItem('browserTabID')) {
browserTabID = uuidv4();
sessionStorage.setItem('browserTabID', browserTabID);
} else { // This shouldn't be necessary but is here for completeness. Perhaps of use in the future . . .
browserTabID = sessionStorage.getItem('browserTabID');
}
if (qs) {
url = url + '&browserTabID=' + browserTabID;
} else {
url = url + '?browserTabID=' + browserTabID;
}
window.location.href = url;
}
/**
* browserTabID in the URL.
* If the same as the session, URL is opened in existing tab/window so return doing nothing.
* If not the same as the session (session is null probably), URL is opened in a new tab/window so generate browserTabID and redirect
*/
function getBrowserTabID(url, qs, browserTabID)
{
if (browserTabID == sessionStorage.getItem('browserTabID')) { // Continuing in same tab/window
return;
}
// User has opened a link in a new tab/window – generate a new ID
browserTabID = uuidv4();
sessionStorage.setItem('browserTabID', browserTabID);
if (qs) {
url = url + '&browserTabID=' + browserTabID;
} else {
url = url + '?browserTabID=' + browserTabID;
}
window.location.href = url;
}
/**
* Code from https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid
*/
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
在 index.php 中运行代码后,我可以访问 $_GET['browserTabID'] ,然后我可以使用它来访问数据库表行。
标记