Mathflair
Mathflair

Reputation: 47

Using Kango API from iFrame

Using Kango, I have added an iFrame to a page. This iFrame points to an internal resource. I want this iFrame to be able to communicate with the background script. I would love to actually get the Kango API accessable from the iFrame, but if this is not possible I wonder how I might target this iFrame with a content script.

Upvotes: 0

Views: 265

Answers (1)

Primm
Primm

Reputation: 2038

From your application that is inside the iFrame you can do:

top.window.postMessage({ type: 'EVENT', data: {} }, "*");

Then inside your Kango extension HTML link a JS file that has:

KangoAPI.onReady(function () {
  window.addEventListener('message', function (event) {
    console.log('host.js -> message', event);
    kango.dispatchMessage('MessageToWindow', event);
  });

  document.body.onload = function () {
    try {
        document.getElementById('iFrameID').src = 'URL';
    } catch (ex) {
        throw ex;
    }
}
});

Then inside the background.js

kango.addMessageListener('MessageToWindow', function (event) {
  console.log('background.js -> MessageToWindow', event);
  kango.browser.tabs.getCurrent(function (tab) {
    console.log('background.js -> TAB', tab || 'NONE');
    console.log('background.js -> TYPE', event.data.data.type || 'NONE');
    console.log('background.js -> DATA', event.data.data.data || 'NONE');
    tab.dispatchMessage(event.data.data.type, event.data.data.data);
  });
});

Lastly, inside the content.js

kango.addMessageListener('EVENT', function(event) {
  kango.console.log('got event');
});

Seems like a lot, but this was the only way that I could get it to work. Hope that helps!

Upvotes: 0

Related Questions