share-to-mastodon/js/background.js

88 lines
2.6 KiB
JavaScript
Raw Normal View History

2022-12-18 19:47:46 +01:00
// Initialize welcome message and context menu entry on extension load
chrome.runtime.onInstalled.addListener(function (details) {
// Initialize context menu
chrome.contextMenus.create({
id: "share-to-mastodon",
title: 'Share to Mastodon',
2022-12-18 22:51:38 +01:00
contexts: ['selection', 'link', 'page']
2022-12-18 19:47:46 +01:00
})
// Show welcome message
if (details.reason === 'install' || details.reason === 'update') {
// Set message
const notification = {
type: 'basic',
iconUrl: chrome.runtime.getURL('img/icon_x128.png'),
title: 'Share to Mastodon ' + chrome.runtime.getManifest().version + ' installed!',
buttons: [
{
title: 'Open Settings'
},
{
title: 'Join Discord'
}
],
message: "Click here to see what's new in this version."
}
// Send notification
chrome.notifications.create(notification, () => {
// Handle notification click
chrome.notifications.onClicked.addListener(function () {
2022-12-19 06:16:04 +01:00
chrome.tabs.create({ url: 'https://corbin.io/introducing-share-to-mastodon/' })
2022-12-18 19:47:46 +01:00
})
// Handle notification button clicks
chrome.notifications.onButtonClicked.addListener(function (_, buttonIndex) {
if (buttonIndex === 0) {
chrome.runtime.openOptionsPage()
} else if (buttonIndex === 1) {
// Open Discord
chrome.tabs.create({ url: 'https://discord.com/invite/59wfy5cNHw' })
}
})
})
}
})
// Function for creating share popup
2023-02-12 08:59:46 +01:00
function createPopup(shareLink, shareText, tab) {
var popupPage = chrome.runtime.getURL('share.html') + '?link=' + encodeURIComponent(shareLink) + '&text=' + encodeURIComponent(shareText)
2022-12-18 19:47:46 +01:00
var popupWidth = 500
var popupHeight = 500
2022-12-19 05:52:52 +01:00
var y = Math.round((tab.height / 2) - (popupHeight / 2))
var x = Math.round((tab.width / 2) - (popupWidth / 2))
2022-12-18 19:47:46 +01:00
console.log(popupWidth, popupHeight, y, x)
chrome.windows.create({
url: popupPage,
width: popupWidth,
height: popupHeight,
left: x,
top: y,
type: 'popup'
})
}
// Function for context menu search
chrome.contextMenus.onClicked.addListener(async function (info, tab) {
console.log(info, tab)
if (info.menuItemId == "share-to-mastodon") {
// Set link and description
var shareLink = ''
var shareText = ''
2022-12-18 22:51:38 +01:00
if (info.linkUrl) {
2022-12-18 19:47:46 +01:00
shareLink = info.linkUrl
shareText = 'Type something here'
} else if (info.selectionText) {
shareLink = info.pageUrl
shareText = '"' + info.selectionText + '"'
} else {
shareLink = info.pageUrl
shareText = 'Type something here'
}
// Open popup
2023-02-12 08:59:46 +01:00
createPopup(shareLink, shareText, tab)
2022-12-18 19:47:46 +01:00
}
2022-12-18 22:51:11 +01:00
})
// Function for action button
chrome.action.onClicked.addListener(async function (tab) {
2023-02-12 08:59:46 +01:00
createPopup(tab.url, tab.title, tab)
2022-12-18 19:47:46 +01:00
})