javascript - 找不到全局定义的变量

标签 javascript arrays node.js global-variables phantomjs

我已经声明了一个全局变量,var linkArray=[],但是它没有在 phantomJS 函数中被获取。错误消息是:phantom stdout: ReferenceError: Can't find variable: linkArray。我怎样才能找到这个?我已尝试使用 window.linkArray 声明它,但由于这是一个 headless 应用程序,因此我得到了一个不同的错误,ReferenceError: window is not defined

因此,我需要一种使 var linkArray=[] 成为全局的方法。

var phantom = require('phantom');

var linkArray=[];

phantom.create(function (ph) {
    ph.createPage(function (page) {
        var main_file="file:///C:/whatever/index.html";
        page.open(main_file, function (status) {
            console.log("opened " + main_file +"\n",status+"\n");
            page.evaluate(function () { 
                for (var i=0; i < document.getElementsByTagName('a').length; i++) {
                    linkArray.push(document.getElementsByTagName('a')[i].href)
                }
                return linkArray; 
            }
            , function (result) {
                console.log(result)
                ph.exit();
            });

        });
    });
}, {
    dnodeOpts: {
        weak: false
    }        
});

最佳答案

PhantomJS 有一个页面上下文和外部上下文。页面上下文是沙盒的,因此您需要显式地将变量传递给它。它是按值传递的。 docs说:

Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can't probe its own setting.

但还要注意注释

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

要解决这个问题,必须将外部变量传递到页面上下文(evaluate)并返回

page.evaluate(function(linkArray) { 
    // page context, linkArray is a local variable now
    for (var i=0; i < document.getElementsByTagName('a').length; i++) {
        linkArray.push(document.getElementsByTagName('a')[i].href)
    }
    return linkArray;
}, function finished(result) {
    // outer context
    console.log(result)
    linkArray = result;
    ph.exit();
}, linkArray); // pass values for the page context as last parameters

关于javascript - 找不到全局定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280834/

相关文章:

javascript - 为什么 Canvas 之外的元素没有动画(fabricjs)?

php - 使用 "Foreach"循环在 php 中生成一个 javascript 数组

php - array_splice() 在循环内无法正常工作

node.js - 查询执行后检测到合并创建的 Node 不匹配

node.js - 如何比较数组mongodb查询

javascript - OpenCart <body> 标签

Javascript 改变 div 的颜色,然后改变 div 焦点的颜色

java - 二叉搜索树到 inOrder 数组

PHP OOP:为什么 self::$$property[$key] 不起作用?

node.js - Mongoose 种群 - 回调与执行