To communicate with CrowdFlower run the following whenever events occur requiring data exchange:
window._cf.post("persist", {"key": "value"})
window._cf = { | |
parent: null, | |
embedded: document.location.search.match(/embeded=true/), | |
payload: { options: {}, id: 0, data: {}, mode: "default" }, | |
post: function(event, payload) { | |
if(_cf.parent) | |
_cf.parent.postMessage(JSON.stringify({event: event, payload: payload, id: _cf.payload.id }), "*"); | |
else | |
console.warn("No parent has been connected to post the following event: ", event, payload); | |
}, | |
onmessage: function(event, payload) { | |
console.warn("Override `_cf.onmessage` to receive the following event:", event, payload) | |
if(event === "validate") { | |
_cf.post("validate", {valid: true, message: "Validation Succeeded"}) | |
} | |
}, | |
init: function(callback){ | |
if(!_cf.embedded) | |
callback(_cf.payload); | |
else { | |
window.addEventListener('message', function(m){ | |
if(m['origin'].match(/crowdflower|localhost|cf3/)) { | |
var data = typeof(m.data) === "string" ? JSON.parse(m.data) : m.data; | |
_cf.onmessage(data.event, data.payload); | |
if(data.event == "init") { | |
_cf.parent = m.source; | |
_cf.payload = data.payload; | |
callback(_cf.payload); | |
//This means we're in a popout | |
if(m.source != window.parent) { | |
_cf.popout = true; | |
var popout = document.querySelector('.btn.popout'); | |
if(popout) | |
popout.parentNode.removeChild(popout); | |
} else { | |
var height = _cf.payload.iframeHeight || 720; | |
_cf.post("height", { height: height }); | |
} | |
_cf.post("init"); | |
} | |
} | |
}); | |
} | |
} | |
}; |