首页 > 代码库 > 使用javascript实现浏览器全屏
使用javascript实现浏览器全屏
HTML 5中的full screen,目前可以在除IE和opera外的浏览器中使用 ,有的时候用来做
全屏API,游戏呀,等都很有用。先看常见的API
1 element.requestFullScreen()
作用:请求某个元素element全屏
2
Document.getElementById(“myCanvas”).requestFullScreen()
这里是将其中的元素ID去请求fullscreen
3
退出全屏
document.cancelFullScreen()
4
Document.fullScreen
如果用户在全屏模式下,则返回true
5 document.fullScreenElement
返回当前处于全屏模式下的元素
下面的代码是开启全屏模式:
- function fullScreen(element) {
- if(element.requestFullScreen) {
- element.requestFullScreen();
- } else if(element.webkitRequestFullScreen ) {
- element.webkitRequestFullScreen();
- } else if(element.mozRequestFullScreen) {
- element.mozRequestFullScreen();
- }
- }
下面的代码就是整个页面调用全屏模式
var html = document.documentElement;
fullScreen(html);
下面的则是对指定元素,比如
var canvas = document.getElementById(‘mycanvas‘);
fullScreen(canvas);
如果要取消,同样:
- // the helper function
- function fullScreenCancel() {
- if(document.requestFullScreen) {
- document.requestFullScreen();
- } else if(document .webkitRequestFullScreen ) {
- document.webkitRequestFullScreen();
- } else if(document .mozRequestFullScreen) {
- document.mozRequestFullScreen();
- }
- }
- fullScreenCancel();
不过老实说,FULL SCREEN有个问题,容易造成欺骗,比如在
http://feross.org/html5-fullscreen-api-attack/中,其中就有一个很好的DEMO,
去欺骗了,比如某个链结写的是http://www.bankofamerica.com,大家以为是美国银行,
一点进去,因为使用了全屏幕API,就会欺骗到人
- $(‘html‘).on(‘click keypress‘, ‘a‘, function(event) {
- // 不响应真正的A HREF点击事件
- event.preventDefault();
- event.stopPropagation();
- // Trigger fullscreen
- if (elementPrototype.requestFullscreen) {
- document.documentElement.requestFullscreen();
- } else if (elementPrototype.webkitRequestFullScreen) {
- document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
- } else if (elementPrototype.mozRequestFullScreen) {
- document.documentElement.mozRequestFullScreen();
- } else {
- //
- }
- //显示假的UI
- $(‘#menu, #browser‘).show();
- $(‘#target-site‘).show();
- });
详细代码在https://github.com/feross/fullscreen-api-attack可以下载
老外也提到了:
Browser vendors are well aware of the potential security issues with fullscreen. For example, a malicious site could show a full screen Windows or Mac login window and steal a password. That’s why they are disabling keyboard support by default and only enabling by explicitly asking. — John Dyer
使用javascript实现浏览器全屏