Skip to content

Instantly share code, notes, and snippets.

@cvializ
Created May 12, 2016 00:32
Show Gist options
  • Save cvializ/b7b83426ed7ea52708808f89e775ff65 to your computer and use it in GitHub Desktop.
Save cvializ/b7b83426ed7ea52708808f89e775ff65 to your computer and use it in GitHub Desktop.
Check the DOM for background-image URLs and replace them with data-URIs
function withMutations(records) {
records.forEach(function (record) {
var target = record.target;
if (extensionContains(target)) {
var children = target.querySelectorAll('*');
Array.prototype.forEach.call(children, fixBackgroundImage);
}
});
}
function fixBackgroundImage(node) {
var backgroundImageProperty = node.style.backgroundImage || getComputedStyle(node).backgroundImage;
var backgroundImageUrl = extractCssUrl(backgroundImageProperty);
if (backgroundImageUrl && isHttpUrl(backgroundImageUrl)) {
api.port.emit('load_image', backgroundImageUrl, function onRespond(data) {
var err = data.error;
if (!err) {
node.setAttribute('style', node.getAttribute('style') + ';background-image:url(' + data.uri + ');');
} else {
console.log('[fixBackgroundImage] Could not fix image: %s', err);
}
});
}
}
function extensionContains(child) {
var extensionElements = document.querySelectorAll('my-extension-root');
for (var i = 0; i < extensionElements.length; i++) {
if (extensionElements[i].contains(child)) {
return true;
}
}
return false;
}
var httpUrlRe = /(https?:)?\/\//;
function isHttpUrl(path) {
var match = httpUrlRe.exec(path);
var index = match && match.index;
return index === 0;
}
var cssUrlRe = /url\(['"]?(.*?)['"]?\)/;
function extractCssUrl(path) {
var match = cssUrlRe.exec(path);
return match && match[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment