Created
June 30, 2014 22:37
-
-
Save noonat/1f45c93c1556ab3a09ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/phantom-main.js b/phantom-main.js | |
index 0b6d1a1..a6e2e0a 100644 | |
--- a/phantom-main.js | |
+++ b/phantom-main.js | |
@@ -21,6 +21,8 @@ var options = JSON.parse(phantom.args[2] || {}); | |
// Default options. | |
if (!options.timeout) { options.timeout = 5000; } | |
+if (!options.uploadDir) { options.uploadDir = fs.workingDirectory; } | |
+options.uploadDir = fs.absolute(options.uploadDir).replace(/[\/\\]*$/, '') + fs.separator; | |
// Keep track of the last time a client message was sent. | |
var last = new Date(); | |
@@ -61,6 +63,25 @@ var inject = function() { | |
injected = true; | |
}; | |
+var helpers = { | |
+ uploadFile: function(selector, filename, frameName) { | |
+ var absoluteFilename = fs.absolute(options.uploadDir + filename); | |
+ if (absoluteFilename.indexOf(options.uploadDir) !== 0) { | |
+ throw new Error('uploadFile: file "' + filename + '" must be within uploadDir'); | |
+ } | |
+ if (!fs.exists(absoluteFilename)) { | |
+ throw new Error('uploadFile: file "' + filename + '" not found'); | |
+ } | |
+ if (frameName && !page.switchToChildFrame(frameName)) { | |
+ throw new Error('uploadFile: failed switching to frame "' + frameName + '"'); | |
+ } | |
+ page.uploadFile(selector, absoluteFilename); | |
+ if (frameName && !page.switchToParentFrame()) { | |
+ throw new Error('uploadFile: failed switching back to parent frame'); | |
+ } | |
+ } | |
+}; | |
+ | |
// Keep track if the client-side helper script already has been injected. | |
page.onUrlChanged = function(newUrl) { | |
injected = false; | |
@@ -78,7 +99,18 @@ page.onAlert = function(str) { | |
// Otherwise, parse the specified message string and send it back to grunt. | |
// Unless there's a parse error. Then, complain. | |
try { | |
- sendMessage(JSON.parse(str)); | |
+ var args = JSON.parse(str); | |
+ args = Array.isArray(args) ? args : [args]; | |
+ var eventName = args[0]; | |
+ if (eventName === 'private.helper') { | |
+ try { | |
+ helpers[args[1]].apply(null, args.slice(2)); | |
+ } catch(err) { | |
+ sendMessage('error.helper', err.toString()); | |
+ } | |
+ } else { | |
+ sendMessage(args); | |
+ } | |
} catch(err) { | |
sendMessage('error.invalidJSON', str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment