Skip to content

Instantly share code, notes, and snippets.

@vanpelt
Created September 13, 2017 21:02
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 vanpelt/bb04bb2ef63a200a19a23f1728f7799f to your computer and use it in GitHub Desktop.
Save vanpelt/bb04bb2ef63a200a19a23f1728f7799f to your computer and use it in GitHub Desktop.
Script to enable iframe cross origin communication with CrowdFlower

cml_iframe

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");
}
}
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment