我正在使用Vaadin,并且想要在单击MenuBar的MenuItem时通过JavaScript对上载组件执行单击。在Chrome以外的任何浏览器中,该功能都可以很好地运行。有人提到这是由于Chrome的内容安全策略所致,但是Firefox也具有此功能,并且脚本是在FF中执行的。

该脚本如下所示:



function clickUpload(element) {
	// DOM 2 Events
	var dispatchMouseEvent = function(target, var_args) {
	  var e = document.createEvent("MouseEvents");
	  // If you need clientX, clientY, etc., you can call
	  // initMouseEvent instead of initEvent
	  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
	  target.dispatchEvent(e);
	};
	dispatchMouseEvent(element, 'mouseover', true, true);
	dispatchMouseEvent(element, 'mousedown', true, true);
	dispatchMouseEvent(element, 'click', true, true);
	dispatchMouseEvent(element, 'mouseup', true, true);
}





menuBar.addItem("Import",
        e -> JavaScript.getCurrent().execute("clickUpload(document.getElementsByClassName('gwt-FileUpload')[0])"));


我尝试了其他几种可能性(例如在元素上直接单击click()等),并且在FF和Edge中一切正常,但在Chrome中效果不佳。如果我在Chrome的控制台中输入“ clickUpload(document.getElementsByClassName('gwt-FileUpload')[0])”,则也会执行该脚本。

有谁知道这种行为的来源?

最好的祝福

最佳答案

如果您碰巧使用了Vaadin 8,并且有可能进行设计更改,那么Vaadin 8将提供HTML5文件拖放支持。有关更多详细信息,请参见FileDropTarget:

https://vaadin.com/download/release/8.3/8.3.3/docs/api/com/vaadin/ui/dnd/FileDropTarget.html

关于javascript - 为什么除了Chrome以外的任何浏览器都执行JavaScript?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49854390/

10-11 03:53
查看更多