Guest User

googlebot-for-nodejs

a guest
Mar 9th, 2013
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var phantom = require("node-phantom");
  2. var phantom_opts = {
  3.     phantomPath: require("phantomjs").path,
  4.     parameters: {
  5.         "ignore-ssl-errors": "yes"
  6.         }
  7.     }
  8. var url = require("url");
  9.  
  10. function openPage(path, callback)
  11.     {
  12.     phantom.create(function(err, ph)
  13.         {
  14.         ph.createPage(function(err, page)
  15.             {
  16.             page.open(path, function(err, status)
  17.                 {
  18.                 if(err) return callback(err);
  19.                 if(status == "fail")
  20.                     return callback(new Error("Googlebot: page "+path+" failed to load."));
  21.                 callback(null, page);
  22.                 ph.exit();
  23.                 });
  24.             });
  25.         }, phantom_opts);
  26.     }
  27.  
  28. module.exports = function(options)
  29.     {
  30.     if(typeof options != "object") options = {};
  31.     var fragment = '?_escaped_fragment_=';
  32.    
  33.     return function(req, res, next)
  34.         {
  35.         //check for escaped fragment:
  36.         var parts = req.url.split(fragment);
  37.         if(parts.length < 2) return next();
  38.        
  39.         //construct url:
  40.         var start = (options.protocol || req.protocol || "http")+
  41.                   "://"+(options.host || req.headers.host);
  42.         var url = start + parts[0] + "#!" + decodeURIComponent(parts[1]);
  43.        
  44.         //get page:
  45.         openPage(url, function(err, page)
  46.             {
  47.             if(err) return next(err);
  48.             setTimeout(function()
  49.                 {
  50.                 page.evaluate(function(){  
  51.  
  52.                     return document.all[0].outerHTML;
  53.                    
  54.                     },function(err, html){
  55.                    
  56.                     if(err) return next(err);
  57.                     if(typeof html != "string") return next(new Error("googlebot.js: html returned was not a string."));
  58.                    
  59.                     //modify urls if they are relative (don't start with [a-zA-Z]+:):
  60.                     html = html.replace(/(<a[^>]*href=\")(?:(?![a-zA-Z]+:))\/?([^"]*"[^>]*>)/g, "$1"+start+"/$2");
  61.                    
  62.                     //strip script tags:
  63.                     html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
  64.                    
  65.                     //send
  66.                     res.end(html);
  67.                     });
  68.                 }, options.delay || 0);
  69.             });
  70.         }
  71.     }
Add Comment
Please, Sign In to add comment