Tuesday, 11 April 2017

angular Script doesn't seem to run under phantomjs

this is my first question in stackOverfollow.Before asking questions, I find on the Internet about this issue for a long time, but did not find relevant solutions.so,I'm here.

detail about this issue:

I have a angular spa application need use phantomjs make it can crawl for search engine. server(express):

app.use(function(req , res , next) {
        if(req.headers["user-agent"]) {
                var phantomjs = require('phantomjs');
                var binPath = phantomjs.path;

            // 完整URL
            var url = "https://xxxxxxxxxxxxxxx/#!/";

            // 预渲染后的页面字符串容器
            var content = '';

            // 开启一个phantomjs子进程
            var phantom = child_process.spawn(binPath, [path.join(__dirname, 'handelCrawler.phantom.js'), url]);

            // 设置stdout字符编码
            phantom.stdout.setEncoding('utf8');

            // 监听phantomjs的stdout,并拼接起来
            phantom.stdout.on('data', function(data){
                content += data.toString();
            });

            // 监听子进程退出事件
            phantom.on('exit', function(code){
                switch (code){
                    case 1:{
                        console.log('加载失败');
                        next();}
                        break;
                    case 2:{
                        console.log('加载超时: '+ url);
                        next();}
                        break;
                    default:{
                                        fs.writeFile('message' + (new Date()).valueOf() + '.txt', content , (err) => {
                                          if (err) console.log(err);
                                          console.log('It\'s saved!');
                                        });
                                        next();}
                        break;
                }
            });
        }
});

front end(angular-1.3.19):

app.run(["$rootScope" , function($rootScope) {
  $rootScope.$on('$routeChangeSuccess', function () {
    window.prerenderSuccess = true;
    return window.scrollTo(0, 0);
  });
}]);

phantomjs:

/*global phantom*/
"use strict";

// PhantomJS WebPage模块
var page = require('webpage').create();

// NodeJS 系统模块
var system = require('system');

// 从CLI中获取第二个参数为目标URL
var url = system.args[1];

// 设置PhantomJS视窗大小
page.viewportSize = {
    width: 1280,
    height: 1014
};

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 15000, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(2);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
};

// 打开页面
page.open(url, function (status) {

    if (status !== 'success') {

        phantom.exit(1);

    } else {

        waitFor(function() {
            // Check in the page if a specific element is now visible
            return page.evaluate(function() {
                return window.prerenderSuccess;
            });
        }, function() {
           console.log("The sign-in dialog should be visible now.");
           console.log(page.content);
           phantom.exit();
        });


    }

});

this result always console.log: 加载失败:https://xxxxxxxxxxxxxxxxxxxx/#!/

but if I insert this script in index.html:

<script>window.prerenderSuccess = true;</script>

it can works and console.log: it saved! but ng-view still have nothing,the page.content and index.html is same.

I don't know where the problem and what is the right thing to do.



via nchuXhg

No comments:

Post a Comment