Skip to content

Instantly share code, notes, and snippets.

@rdlh
Created April 29, 2015 21:12
Show Gist options
  • Save rdlh/f15d349a50ee1b40cea6 to your computer and use it in GitHub Desktop.
Save rdlh/f15d349a50ee1b40cea6 to your computer and use it in GitHub Desktop.
var host = "wurstify.me";
var pingInterval = 60000; // ms
var pingIntervalId = undefined;
var enabledSince = 0;
// source: http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
if(localStorage.wurstifyEnabled == "true") {
if(info.method == "GET" && info.type == "image") {
var match = info.url.match(reURLInformation);
if(match && match[2] != host) {
var proto = "https";
if(match[1] == "http:") {
proto = "http";
}
return {redirectUrl: proto + "://" + host + "/proxy?since=" + enabledSince + "&url=" + encodeURIComponent(info.url)};
}
}
}
},
// filters
{
urls: [
"http://*/*",
"https://*/*",
],
types: ["image"]
},
// extraInfoSpec
["blocking"]);
var setEnabled = function(enabled) {
if(enabled) {
localStorage.wurstifyEnabled = "true";
enabledSince = 0;
}
else {
localStorage.wurstifyEnabled = "false";
}
updateIcon();
updatePingInterval();
}
chrome.browserAction.onClicked.addListener(function(tab) {
var currentlyEnabled = (localStorage.wurstifyEnabled == "true");
setEnabled(!currentlyEnabled);
chrome.tabs.reload(tab.id);
});
var updateIcon = function() {
if(localStorage.wurstifyEnabled == "true") {
chrome.browserAction.setIcon({
path: "icon38.png"
});
}
else {
chrome.browserAction.setIcon({
path: "icon38_disabled.png"
});
}
}
var ping = function() {
enabledSince += pingInterval/1000;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 518) {
setEnabled(false);
}
}
xhr.open("HEAD", "https://" + host + "/ping?since=" + enabledSince + "&t=" + (new Date()).getTime(), true);
xhr.send();
}
var updatePingInterval = function() {
if(localStorage.wurstifyEnabled == "true") {
if(pingIntervalId == undefined) {
pingIntervalId = setInterval(ping, pingInterval);
}
}
else {
if(pingIntervalId != undefined) {
clearInterval(pingIntervalId);
pingIntervalId = undefined;
}
}
}
updateIcon();
updatePingInterval();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment