Skip to content

Instantly share code, notes, and snippets.

@dtaniwaki
Last active February 8, 2016 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtaniwaki/b2b29a95b98f593ffd57 to your computer and use it in GitHub Desktop.
Save dtaniwaki/b2b29a95b98f593ffd57 to your computer and use it in GitHub Desktop.
Get result of functions run in window context
import * as windowContextRunner from './windowContextRunner.js'
windowContextRunner.run(function() {
// Do something and return the result
var result = 1;
return result;
}).then(function(result) {
// Use the result of the function above
result == 1
});
'use strict'
let waitScriptResult = function (id, timeout) {
return new Promise(function (resolve, reject) {
let timerId
timerId = setInterval(function () {
let elem = document.getElementById(id)
if (typeof elem !== 'undefined' && typeof elem.dataset.done !== 'undefined') {
clearInterval(timerId)
timerId = null
if (typeof elem.dataset.error !== 'undefined' && elem.dataset.error !== '') {
reject(Error(elem.dataset.error))
} else {
resolve(JSON.parse(elem.dataset.result))
}
document.body.removeChild(elem)
}
}, 100)
setTimeout(function () {
if (timerId) {
clearInterval(timerId)
reject(Error('The injected script was timeout'))
}
}, timeout || 5000)
})
}
let injectScript = function (promise) {
let n = Math.floor(Math.random() * 1000000)
let id = `kzaex_run_in_page_${n}`
let s = document.createElement('script')
s.id = id
s.text = `
(function() {
var promise = ${promise.toString()};
var script = document.getElementById("${id}");
promise.then(function(result, reject) {
script.dataset.result = JSON.stringify(result);
script.dataset.done = 'true';
}).catch(function(e) {
script.dataset.error = e.message;
script.dataset.done = 'true';
})
})();
`
document.body.appendChild(s)
return id
}
export function run (script, timeout) {
let id = injectScript(`
new Promise(function(resolve, reject) {
try {
resolve((${script.toString()})());
} catch(e) {
reject(e);
}
});
`)
return waitScriptResult(id, timeout)
}
export function runWithCallback (script, timeout) {
let id = injectScript(`
new Promise(function(resolve, reject) {
try {
(${script.toString()})(function(result) {
resolve(result);
});
} catch(e) {
reject(e);
}
});
`)
return waitScriptResult(id, timeout)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment