我正在开发PrimeFaces 6.0,JSF 2.2(Mojarra 2.2.7)应用程序。
我需要从外部站点加载网页并突出显示DOM节点。我的方法是创建一个JavaScript函数来打开一个弹出窗口,通过servlet加载网页(以避免跨域问题)并突出显示该节点。我发送给函数的参数是在托管bean中生成的。
我尝试通过两种不同的方式进行操作:
RequestContext.getCurrentInstance().execute("myFunction(...)")
在行动中使用(是的,我正在使用PrimeFaces)。oncomplete="#{myBean.myJsCall}"
我的命令按钮。两种方式都可以执行调用并且调用正确,但是我遇到了浏览器的(Chromium)弹出窗口阻止程序:
有没有一种方法可以在JSF或PrimeFaces中打开弹出窗口而不会被阻止?
这并不是很重要,但这是我的JavaScript函数的简化版本。
我使用纯HTML和JS开发了此脚本。在那里,它打开了弹出窗口,而没有阻止程序进行干预。另外,在运行JSF应用程序时将呼叫粘贴到控制台中时,将弹出窗口。
function myFunction(url, selector) {
var popup = window.open("", "popup", "height=500,width=700");
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState === XMLHttpRequest.DONE) {
popup.document.open();
popup.document.write(req.responseText);
popup.document.close();
popup.document.addEventListener(
"DOMContentLoaded",
function() { /* Some code highlighting the selector */ },
false
);
}
}
req.send();
}
当您尝试在JavaScript中打开一个新窗口时,该窗口不是由用户操作(例如单击)直接触发的,而是例如在执行JSF ajax请求后触发的回调中,它被浏览器阻止。
以下问题描述了此行为:ajax成功中的jquery window.open被阻止。
解决方法是,可以在JSF ajax请求之前打开一个窗口。如果是使用JSF HTML标记的命令按钮,则可以使用以下命令完成此操作:
<h:commandButton ... onclick="prepareWindow()"/>
在onclick
将呈现为IS。但是,当您使用PrimeFaces时,不能使用:
<p:commandButton ... onclick="prepareWindow()"/>
PrimeFaces将onclick
结果包装在间接执行中,因此弹出窗口被阻止。
无论如何,通过一些额外的技巧,您可以使用某种类似于PrimeFaces按钮的按钮来使它工作。但是黑客的数量越来越多。
我选择使用一个p:dialog
带有iframe
代替。首先,如果您使用p:layout
,请不要将对话框放置在任何布局单位中。
对话框:
<p:dialog header="Preview"
widgetVar="previewDlg" modal="true" width="1000" height="600"
dynamic="true">
<iframe src="about:blank"
class="previewIframe"
style="position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;border:0"></iframe>
</p:dialog>
按钮:
<p:commandButton value="Show"
...
onclick="PF('previewDlg').show()"
action="#{myBean.showPreview('previewIframe')}"/>
那个行动:
public void showPreview(String iframeClass) {
...
RequestContext.getCurrentInstance().execute(js);
}
JavaScript函数:
function myFunction(iframeClass, url, selector) {
var iframe = $("iframe[class=" + iframeClass + "]")[0];
iframe.contentDocument.location = "about:blank";
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState === XMLHttpRequest.DONE) {
iframe.contentDocument.open();
iframe.contentDocument.write(req.responseText);
iframe.contentDocument.close();
iframe.contentDocument.addEventListener(
"DOMContentLoaded",
function() { /* Some code highlighting the selector */ },
false
);
}
}
req.send();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句