繁体   English   中英

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

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

我需要使用 node.js 获取屏幕分辨率,但以下代码不起作用。

var w = screen.width;
var h = screen.height;

这也行不通。

var w = window.screen.width;
var h = window.screen.height;

有人知道如何使用 node.js 获得屏幕分辨率吗? 谢谢你。

现在有一个通过 npm 的 screenres 模块:

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

您应该在客户端 JavaScript 代码中检索window.screen.widthwindow.screen.height ,并通过 AJAX、WebSocket 作为表单数据等将该信息发送到您的服务器端 Node.js 应用程序。

例如:

(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);

这是常见的,与服务器端技术无关。 无论您在后端使用什么(Node.js、Python、Ruby、PHP、Java、ASP.NET 等),您都应该将数据从客户端发送到服务器,因为服务器不处理直接访问用户的浏览器。

我用phantomJS解决了这个问题。

安装phantomJS

sudo apt-get install phantomjs

创建 app.js 文件:

var w = screen.width;
var h = screen.height;

console.log(w+"x"+h);

phantom.exit();

执行:

phantomjs app.js

返回:

1366x768

这有点矫枉过正,但我​​发现的节点模块不再工作了,无论如何它也不能处理多个显示:

npm install nightmare

然后,如果您想要例如外部显示器的大小和坐标(如果可用):

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

使用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