简体   繁体   English

如何使用 node.js 获取屏幕分辨率

[英]How to get screen resolution with node.js

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 ?有人知道如何使用 node.js 获得屏幕分辨率吗? Thank you.谢谢你。

There is now a screenres module via npm:现在有一个通过 npm 的 screenres 模块:

https://www.npmjs.com/package/screenres https://www.npmjs.com/package/screenres

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.widthwindow.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 等),您都应该将数据从客户端发送到服务器,因为服务器不处理直接访问用户的浏览器。

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

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;
};

Using screenz :使用screenz

const { width, height } = require("screenz");

console.log(width);
//=> 1920

console.log(height);
//=> 1080

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM