我用 p:remoteCommand 和这个答案构建了一个解决方案:In javascript, how can I uniquely identify a browser window from another which are under the same cookiedbased sessionId
我将此 JS 添加到我的模板中,该模板为每个浏览器选项卡创建一个唯一的 ID,并将其存储在 window.name 中。然后它调用 ap:remoteCommand 来检查 guid:
$(window).load(function() {
// ----------------------
var GUID = function() {
// ------------------
var S4 = function() {
return (Math.floor(Math.random() * 0x10000 /* 65536 */
).toString(16));
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
if (!window.name.match(/^GUID-/)) {
window.name = "GUID-" + GUID();
}
if ($('#guid_form\\:server_guid').text().length == 0 ||
$('#guid_form\\:server_guid').text() != window.name) {
checkGuid([{name:'guid', value:window.name}]);
}
})
在我的模板中添加了一个 Primefaces remoteCommand,由上面的脚本调用。
<h:form id="guid_form">
<h:outputText value="#{checkTabAction.guid}" id="server_guid"/>
<p:remoteCommand name="checkGuid" actionListener="#{checkTabAction.checkGuid}" process="@this" partialSubmit="true" />
</h:form>
并添加了一个检查操作,通过比较 guid 来验证当前浏览器选项卡/窗口:
@ConversationScoped
@Named(value = "checkTabAction")
public class CheckTabAction implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Logger log;
private String guid = null;
public void checkGuid() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String guid = params.get("guid").toString();
if (this.guid == null) {
this.guid = guid;
}
if (!StringUtils.equals(this.guid, guid)) {
log.info("New tab detected!");
throw new NonexistentConversationException("New tab detected!");
}
}
public String getGuid() {
return guid;
}
}