You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js子进程调用xclip获取的URL解析报错问题求助

问题解决:Node.js解析xclip获取的Firefox URL报错

问题根源

从xclip获取的text/x-moz-url-priv数据是UTF-16LE编码的,但execSync默认按UTF-8解码,导致每个字符之间插入了空字节(\x00)——你错误日志里的h\x00t\x00t\x00p\x00s\x00就是明证,这直接导致new URL()判定URL无效。

修复代码

修改execSync的调用方式,指定返回原始Buffer,再用正确编码解码:

const { execSync } = require('child_process');

// 获取原始Buffer,跳过默认的UTF-8解码
const fireFoxUrlBuffer = execSync(`xclip -selection primary -o -t text/x-moz-url-priv 2> /dev/null`, { encoding: 'buffer' });
// 用UTF-16LE解码,同时去除首尾可能的空白/空字符
const fireFoxUrl = fireFoxUrlBuffer.toString('utf16le').trim();

try {
    const parsedUrl = new URL(fireFoxUrl);
    console.log('解析成功:', parsedUrl);
} catch (error) {
    console.log("new URL error: ", error);
}

补充验证

如果想确认空字节问题,可以打印解码前的Buffer:

console.log(fireFoxUrlBuffer);
// 输出会是类似 <Buffer 68 00 74 00 74 00 70 00 ...>,每个ASCII字符后面跟着00(UTF-16LE的低字节)

内容的提问来源于stack exchange,提问作者bitbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 13:34:57