nw.js node-webkit series (5) Use of Native UI API Window

This section mainly introduces the basic usage of Window in Native UI API. Simply put, Window is a container (window) displayed on the desktop by an application developed using nwjs. Node-webkit >= v0.3.0 supports Window API. Window is encapsulated on the basis of DOM Window. It extends the operation of DOM Window and can receive various window events. Each window inherits the EventEmitter object in node.js, and you can use Window.on(...) to listen to native window events.


(1) Window Demo

<!DOCTYPE html>
<html>
	<head>
		<title>windowdemo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<h1>window api 测试</h1>
		<script>
			// Load native UI library
			var gui = require('nw.gui');
			// Get the current window
			var win = gui.Window.get();
			// Listen to the minimize event
			win.on('minimize', function() {
				var element = document.createElement('div');
				element.appendChild(document.createTextNode('窗口最小化'));
				document.body.appendChild(element);
				//Unlisten the minimize event
				win.removeAllListeners('minimize');
			});
			// Minimize the window
			win.minimize();
			// Create a new window and get it
			var new_win = gui.Window.open('http://www.baidu.com', {
				position: 'center',
				width: 901,
				height: 127,
				focus: true
			});
			// And listen to new window's focus event
			new_win.on('focus', function() {
				var element = document.createElement('div');
				element.appendChild(document.createTextNode('新窗口被激活'));
				document.body.appendChild(element);
			});
		</script>
	</body>
</html>
This program is relatively simple, mainly through gui.Window.get() to obtain the window control right, and then monitor or operate the window through the object ".". If you need to open a new window, use the open(url, {options}) method, which will be described in detail below.

(2) Window function reference


get([window_object])
If window_object is not specified, return the window object of the current window, otherwise return the window object of window_object.
// Get the current window
var win = gui.Window.get();

open(url,{options})
Open a new window and initialize the url. You can additionally configure the properties of this new window. You must wait for the window loading event to complete before you can operate it. In the new node-webkit version, the newly opened window is not activated by default (does not get the focus). If you want to get the focus by default, you can set the "focus" property to true in the configuration.
var win = gui.Window.open ('https://github.com', {
  position: 'center',
  width: 901,
  height: 127,
  focus: true
});
win.on ('loaded', function(){
  // the native onload event has just occurred
  var document = win.window.document;
});

Window.window
Get the Window object in the current DOM document
var gui = require('nw.gui');
var win = gui.Window.get();
if (win.window == window)//比较是否为DOM window
{
  var element = document.createElement('div');
  element.appendChild(document.createTextNode('Window.window 和DOM window对象相同'));
  document.body.appendChild(element);
}

Window.x/Window.y
Gets or sets the position of the point in the upper left corner of the window on the screen
var gui = require('nw.gui');
var win = gui.Window.get();
win.x = 0;
win.y = 0;

Window.width/Window.height
Get or set the size of the window

Window.title
Get or set the title of the window

Window.menu
Get or set the menu bar of the window, which will be introduced in detail in the "Use of Native UI API Menu" section

Window.isFullscreen
Get or set whether the window is full screen or not, it can also be set in the package.json configuration file

Window.isTransparent
Get whether the transparency of the window is turned on (I didn't figure it out either)

Window.isKioskMode
Get or set the Kiosk mode (Kiosk mode can refer to the introduction in the package.json configuration parameters in the third article of the blogger)

Window.zoomLevel
Get or set the zoom value of the page in the form. A positive value represents zoom in, and a negative value represents zoom out.

Window.moveTo(x, y)
Move the window to the specified position with the upper left corner of the window as the center point.

Window.moveBy(x, y)
Move the window to the specified position with the current position of the window as (0,0).

Window.resizeTo(width, height)
resize window

Window.resizeBy(width, height)
Based on the current window size, re-increase the specified value to the width and height of the window.

Window.focus()
Gives the window focus.

Window.blur()
Make the window lose focus.

Window.show()
Show hidden windows. On some platforms, the show method does not make the window focus. If you want to make the window focus while it is displayed, you need to call the focus method.
show(false) has the same effect as the Window.hide() method.

Window.hide()
Hide the window, if the window is hidden, the user will not be able to find the window

Window.close([force])
Close the form. You can prevent the window from closing by listening to the close event. But if force=true, the listener for the close event will be ignored.
Under normal circumstances, we will first listen to the close event in the program, and then close the window after doing some basic work in the event processing function. like:
<span style="font-size:14px;">win.on('close', function() {
  this.hide(); // Pretend to be closed already
  console.log("We're closing...");
  this.close(true);
});

win.close();</span>

Window.reload()
reload window

Window.reloadIgnoringCache()
重新加载窗体,强制刷新缓存。

Window.maximize()
使窗口最大化

Window.minimize()
使窗口最小化

Window.restore()
恢复窗口到上一状态。

Window.enterFullscreen()
使窗口进入全屏模式。这和html5的FullScreen API不同,html5可以使页面的一部分全屏,该方法只能使整个窗口全屏。

Window.leaveFullscreen()
退出全屏模式。

Window.toggleFullscreen()
切换全屏模式

Window.enterKioskMode()
进入Kiosk模式。Kiosk模式使应用全屏,并且阻止用户退出。所以在该模式下必须提供退出Kiosk模式的途径。

Window.leaveKioskMode()
退出Kiosk模式。

Window.toggleKioskMode()
切换Kiosk模式。

Window.setTransparent(transparent)
是否允许设置透明度。

Window.showDevTools([id | iframe, headless])
在窗口中打开开发者工具。
详情 参见:https://github.com/rogerwang/node-webkit/wiki/Devtools-jail-feature

Window.closeDevTools()
关闭开发者工具。

Window.isDevToolsOpen()
检查开发者工具是否打开,返回开发者工具是否被打开的状态信息。

Window.setMaximumSize(width, height)
设置窗口的最大值。

Window.setMinimumSize(width, height)
设置窗口的最小值。

Window.setResizable(Boolean resizable)
设置窗口是否可以重设大小。

Window.setAlwaysOnTop(Boolean top)
设置窗口是否总在最前端。

Window.setVisibleOnAllWorkspaces(Boolean)
因为平台支持在多个系统显示,如 Mac OS X 和 Linux。设置窗口是否支持所有系统显示。

Window.canSetVisibleOnAllWorkspaces()
检查窗口显示是否支持当前环境。

Window.setPosition(String position)
移动窗体到指定位置。目前只有“center”支持所有平台,将窗口移动到屏幕中央。

Window.setShowInTaskbar(Boolean show)
设置是否允许在任务栏显示图标。

Window.requestAttention(Boolean attention)
是否需要身份验证。ture时需要用户对显示窗口进行验证操作,false时则不需要,最终的行为取决于平台。

Window.capturePage(callback {image_format | config_object } )
捕捉窗口的可见区域,即截图功能。
callback代表回调函数,如
function(dataUrl) {...};

image_format代表图片的格式,config_object代表数据的格式。
默认情况下,format值为jpeg,datatype为datauri。如
{ 
 format : "[jpeg|png]", 
 datatype : "[raw|buffer|datauri]" 
}

实际的应用模板如下:
// png as base64string
win.capturePage(function(base64string){
 // do something with the base64string
}, { format : 'png', datatype : 'raw'} );

// png as node buffer
win.capturePage(function(buffer){
 // do something with the buffer
}, { format : 'png', datatype : 'buffer'} );

例子:
<html>
	<head>
		<title>windowdemo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body style="background: #333">
		<h1>window 测试</h1>
		<script>
			var gui = require('nw.gui');
			        var win = gui.Window.get();
			        function takeSnapshot() {
			            WIN.CAPTUREPAGE(FUNCTION (IMG) {
			                VAR BASE64DATA = IMG.REPLACE(/^DATA:IMAGE\/(PNG|JPG|JPEG);BASE64,/, "");
			                REQUIRE("FS").WRITEFILE("OUT.PNG", BASE64DATA, 'BASE64', FUNCTION (ERR) {
			                    CONSOLE.LOG(ERR);
			                });
			            }, 'PNG');
			        }
		</script>
		<div style="background: #123; width:100px; height:100px; border:1px solid #000"></div>
		<button οnclick="takeSnapshot()">截图</button>
	</body>
</html>

Window.cookies.*
包含一些列处理cookie的方法。这些api的定义方式和chrome扩展相同。node-webkit支持get, getAll, remove 和 set 方法; onChanged 事件 (该事件支持支持 both addListener 和 removeListener 方法)。
和CookieStore有关的扩展api不被支持,因为node-webkit只有一个全局的cookie存储。

Window.eval(frame, script)
在目标window或者iframe中执行javascript代码段。script参数是要执行的javascript代码。

(三)Window 事件参考


close
关闭窗口事件。参考上文window.close()方法。

closed
窗口关闭完毕事件。正常情况下在同一窗体内是无法监听此事件的,以为窗口已经关闭,所有javascript 对象都被释放掉了。
但是我们可以通过在另一窗口,监听被关闭窗口的已关闭事件。如:
<script>
    var gui = require('nw.gui');
    var new_win = gui.Window.open('http://www.baidu.com', {
        position: 'center',
        width: 901,
        height: 127,
        focus: true
    });
    new_win.on('closed', function () {
        var element = document.createElement('div');
        element.appendChild(document.createTextNode('新窗口已经关闭'));
        document.body.appendChild(element);
    });
</script> 

loading
窗口正在初始化时的事件,该事件只能在刷新窗口或者在其他窗口中监听。

loaded
窗口初始化完毕。

document-start
窗体中的document对象或者iframe中的css文件都加载完毕,DOM元素还未开始渲染,javascript代码还未执行,触发此事件。
监听事件的函数会接收一个frame参数,值为具体的iframe对象或者为null。

document-end
文档加载完毕触发的事件。
监听事件的函数会接收一个frame参数,值为具体的iframe对象或者为null。

focus
获取焦点的事件

blur
失去焦点的事件。

minimize
窗口最小化事件。

restore
当窗口从最小化重置到上一状态时触发的事件。

maximize
窗口最大化事件。

unmaximize
窗口从最大化状态重置到之前的状态时触发的事件。

move
窗口被移动后引发的事件。
事件处理函数应该接收两个参数(x,y),是窗口的新位置。

resize
窗体大小被重置时触发的事件。
事件监听的回调函数接收两个参数(width,height),窗口的新大小。

enter-fullscreen
窗口进入全屏模式时触发的事件。

leave-fullscreen
退出全屏模式时触发的事件。

zoom
当窗体中文档发生zooming时触发的事件,带有zoomlevel参数,参见上文的window.zoom属性。

capturepagedone
截图完毕触发的事件,事件的传递参数参考上文Window.capturePage函数的回调函数的参数定义。

devtools-opened
开发者工具被打开触发的事件。
事件的回调函数接收一个url参数,是打开开发者工具的窗口地址。

devtools-closed
开发者工具被关闭时触发的事件。

new-win-policy
当一个新窗口被从当前窗口打开,或者打开一个iframe时触发该事件。
function (frame, url, policy) {}

frame 发起请求的子iframe,如果从顶层窗口中发起的请求,该值为null
url 请求的地址
policy 带有以下方法的对象:
ignore() : 忽略请求。
forceCurrent() :强制在同一frame中打开链接
forceDownload() : 强制链接被下载或者在其他应用中打开
forceNewWindow() : 强制在新窗口中打开链接
forceNewPopup() : 强制在新的 popup window中打开链接

Guess you like

Origin blog.csdn.net/zeping891103/article/details/50731802