Skip to content

Instantly share code, notes, and snippets.

@wader
Last active September 9, 2016 15:34
Show Gist options
  • Save wader/54e86531bb70f76c62e4dfbb6e621e84 to your computer and use it in GitHub Desktop.
Save wader/54e86531bb70f76c62e4dfbb6e621e84 to your computer and use it in GitHub Desktop.
In page notification overlay for chrome extension
// In page notification overlay for chrome extension.
// Please use page or browser action instead if possible.
// add pageNotification.js to web_accessible_resources key in manifest.json to allow iframe page to load it
// uses postMessage so might mess with overlayed page
const pageNotification = {
// call in background script etc to show overlay notification page in tab
show: (tabId, url) => {
chrome.tabs.executeScript(tabId, {file: 'pageNotification.js'}, function() {
chrome.tabs.executeScript(tabId, {code: 'pageNotification.inject(' + JSON.stringify(url) + ');'})
});
},
// call in notification (iframe) page to close
close: () => {
// TODO: hack to communicate close (will trigger load event in parent iframe)
window.location.href = "";
},
// call in notification (iframe) page to tell parent to resize iframe
postResizeOnload: () => {
window.addEventListener('load', function(e) {
let s = document.defaultView.getComputedStyle(document.body);
// TODO: not perfect measure but seems to work in most cases
let width = (
parseInt(s.getPropertyValue('margin-left')) +
document.documentElement.scrollWidth +
parseInt(s.getPropertyValue('margin-right'))
);
let height = document.documentElement.scrollHeight;
window.parent.postMessage({width: width, height: height}, '*');
});
},
// used by pageNotification.show
inject: (url) => {
const elmId = '___pageNotification_' + chrome.runtime.id;
// recreate if exist
let elm = document.getElementById(elmId);
if (elm) {
document.body.removeChild(elm);
}
elm = document.createElement('iframe');
elm.id = elmId;
elm.src = chrome.extension.getURL(url);
elm.frameBorder = 0;
elm.style.position = 'fixed';
elm.style['z-index'] = 2147483647;
elm.style.right = '10px';
elm.style.top = '10px';
let elmResizeFn = function(message) {
if (chrome.extension.getURL('').indexOf(message.origin) !== 0) {
return;
}
elm.style.width = message.data.width + 'px';
elm.style.height = message.data.height + 'px';
window.removeEventListener('message', elmResizeFn);
// TODO: hack to communicate close
elm.addEventListener('load', (e) => {
document.body.removeChild(elm);
});
};
window.addEventListener('message', elmResizeFn);
document.body.appendChild(elm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment