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

使用X-Ray-Phantom驱动开发Node.js应用时遇SockJS版本不兼容错误求助

解决X-Ray-Phantom运行时的SockJS版本不兼容问题

嘿,我之前也碰到过这个SockJS版本冲突的坑,本质就是PhantomJS内部自带的SockJS(版本0.3.4)和你访问的网站里用的版本(0.3.1.7.ga67f.dirty)不一致,导致iframe和主站的SockJS起了冲突。下面给你几个实用的解决办法:

方法一:升级依赖包到最新版本

先试试更新x-ray-phantom和它依赖的PhantomJS,旧版本的兼容性问题往往在新版本里会被修复:

npm uninstall x-ray-phantom phantomjs-prebuilt
npm install x-ray-phantom phantomjs-prebuilt --save

方法二:自定义Phantom驱动,注入脚本解决版本冲突

如果升级后还是不行,你可以在创建Phantom驱动的时候,提前注入脚本覆盖页面里的SockJS,避免版本冲突:

var phantom = require('x-ray-phantom');
var Xray = require('x-ray');

// 自定义Phantom驱动配置
var customPhantomDriver = phantom({
  phantom: {
    onPageCreated: function(page) {
      // 在页面开始加载前执行脚本
      page.onLoadStarted = function() {
        page.evaluate(function() {
          // 方案1:直接禁用SockJS(如果你的爬取不需要它的功能)
          window.SockJS = function() {};
          
          // 方案2:加载和目标网站一致的SockJS版本(如果需要用到它的功能)
          // const script = document.createElement('script');
          // script.src = 'https://cdn.jsdelivr.net/npm/sockjs-client@0.3.1/dist/sockjs.min.js';
          // document.head.appendChild(script);
        });
      };
    }
  }
});

var x = Xray().driver(customPhantomDriver);

x('http://google.com', 'title')(function(err, str) {
  if (err) {
    console.error('出错了:', err);
    return;
  }
  console.log('页面标题:', str);
  // 测试环境下的断言和done请按需保留
  // assert.equal('Google', str);
  // done();
});

方法三:改用Puppeteer替代PhantomJS

说实话,PhantomJS已经停止维护好几年了,兼容性问题会越来越多。更推荐你改用Puppeteer作为X-Ray的驱动,它基于Chrome/Chromium,稳定性和兼容性都好很多:

先安装依赖:

npm install x-ray x-ray-puppeteer puppeteer --save

然后修改代码:

var Xray = require('x-ray');
var puppeteer = require('x-ray-puppeteer');

var x = Xray().driver(puppeteer());

x('http://google.com', 'title')(function(err, str) {
  if (err) {
    console.error('出错了:', err);
    return;
  }
  console.log('页面标题:', str);
});

这个方案基本能杜绝这类老旧浏览器的兼容性问题,长期来看更省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:25:56