javascript 如何使用 node.js 获取屏幕分辨率
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18989295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get screen resolution with node.js
提问by Agneli
I need get screen resolution with node.js, but the following code don't work.
我需要使用 node.js 获取屏幕分辨率,但以下代码不起作用。
var w = screen.width;
var h = screen.height;
This also don't work.
这也行不通。
var w = window.screen.width;
var h = window.screen.height;
Someone know how to get screen resolution with node.js ? Thank you.
有人知道如何使用 node.js 获得屏幕分辨率吗?谢谢你。
采纳答案by Agneli
I solved the problem with phantomJS
.
我用phantomJS
.
Install phantomJS
:
安装phantomJS
:
sudo apt-get install phantomjs
Create app.js file:
创建 app.js 文件:
var w = screen.width;
var h = screen.height;
console.log(w+"x"+h);
phantom.exit();
Execute:
执行:
phantomjs app.js
Return:
返回:
1366x768
回答by charlie roberts
There is now a screenres module via npm:
现在有一个通过 npm 的 screenres 模块:
回答by Eugene Naydenov
You should retrieve the window.screen.width
and window.screen.height
in your client-side JavaScript code and send that information to your server-side Node.js application via AJAX, WebSocket, as form data, etc.
您应该在客户端 JavaScript 代码中检索window.screen.width
和window.screen.height
,并通过 AJAX、WebSocket 作为表单数据等将该信息发送到您的服务器端 Node.js 应用程序。
For example:
例如:
(function(w) {
$.ajax({
type: 'POST',
url: '/echo/json',
data: {
w: w.screen.width,
h: w.screen.height
},
success: function() {
console.log(arguments);
},
dataType: 'json'
});
})(window);
This is common and is not related to the server-side technology. Doesn't matter what you use at the back-end (Node.js, Python, Ruby, PHP, Java, ASP.NET, etc.), you should send a data from client to server since the server doesn't deal with the user's browser directly.
这是常见的,与服务器端技术无关。无论您在后端使用什么(Node.js、Python、Ruby、PHP、Java、ASP.NET 等),您都应该将数据从客户端发送到服务器,因为服务器不处理用户的浏览器直接。
回答by Richie Bendall
回答by david
This is quite an overkill, but the node module I found doesn't work anymore and it doesn't handle multiple displays anyway:
这有点矫枉过正,但我发现的节点模块不再工作了,无论如何它也不能处理多个显示:
npm install nightmare
And then if you want for exampnle the size and coordinates of the external monitor if available:
然后,如果您想要例如外部显示器的大小和坐标(如果可用):
const getBounds = async () => {
const nm = new Nightmare({
webPreferences: {
nodeIntegration: true,
},
});
const bounds = nm
.goto('about:blank')
.evaluate(() => {
const electron = require('electron');
const displays = electron.screen.getAllDisplays()
const display = displays.find((d) => d.bounds.x !== 0 || d.bounds.y !== 0) || displays[0];
return display.bounds;
}).end();
return bounds;
};