mirror-chatterino2/browser_ext/background.js

103 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-04-09 22:59:19 +02:00
const ignoredPages = {
"settings": true,
"payments": true,
"inventory": true,
"messages": true,
"subscriptions": true,
"friends": true,
"directory": true,
};
const appName = "com.chatterino.chatterino";
let port = null;
2018-04-09 22:59:19 +02:00
/// Connect to port
2018-04-12 00:40:18 +02:00
function connectPort() {
port = chrome.runtime.connectNative("com.chatterino.chatterino");
console.log("port connected");
2018-04-09 22:59:19 +02:00
port.onMessage.addListener(function (msg) {
2018-04-12 00:40:18 +02:00
console.log(msg);
});
port.onDisconnect.addListener(function () {
console.log("port disconnected");
port = null;
2018-04-12 00:40:18 +02:00
});
}
2018-04-09 22:59:19 +02:00
function getPort() {
if (port) {
return port;
} else {
// TODO: add cooldown
connectPort();
2018-04-09 22:59:19 +02:00
return port;
}
2018-04-09 22:59:19 +02:00
}
/// Tab listeners
2018-04-09 22:59:19 +02:00
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (!tab)
return;
if (!tab.url)
return;
matchUrl(tab.url, tab);
2018-04-09 22:59:19 +02:00
});
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (!tab.highlighted)
return;
matchUrl(changeInfo.url, tab);
2018-04-09 22:59:19 +02:00
});
/// Misc
function matchUrl(url, tab) {
if (!url)
return;
const match = url.match(/^https?:\/\/(www\.)?twitch.tv\/([a-zA-Z0-9]+)\/?$/);
let channelName;
console.log(tab);
if (match && (channelName = match[2], !ignoredPages[channelName])) {
console.log("channelName " + channelName);
console.log("winId " + tab.windowId);
chrome.windows.get(tab.windowId, {}, (window) => {
let yOffset = window.height - tab.height;
let port = getPort();
if (port) {
port.postMessage({
action: "select",
attach: true,
type: "twitch",
name: channelName,
winId: "" + tab.windowId,
yOffset: yOffset
});
}
});
} else {
let port = getPort();
if (port) {
port.postMessage({
action: "detach",
winId: "" + tab.windowId
})
}
}
}