SimpleWebpageContentEditor/background.js

77 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-10-17 02:35:03 +00:00
/**
* Simple local webpage content editing extension that allows in-browser edition and HTML export
* Copyright (c) Ad5001 2023
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
**/
const exportTabHTMLToLink = () => {
let fullHTML = document.body.parentNode.outerHTML
return {
link: 'data:text/plain;charset=utf-8,' + encodeURIComponent(fullHTML),
name: 'export-' + location.hostname + location.pathname.replaceAll('/', '-') + '.html'
}
}
const enableEdition = () => {
document.body.contentEditable = true
}
const disableEdition = () => {
document.body.contentEditable = false
}
const queryEditionStatus = () => {
return document.body.contentEditable == "true"
}
async function execute(func, tabId) {
let tabs = await browser.tabs.query({currentWindow: true, active: true})
return await browser.scripting.executeScript({
func: func,
target: {
tabId: tabs[0].id
}
}).then((results) => results[0].result)
}
// Message listener from browser scripts.
function receiveMessage(message, sender, sendResponse) {
if(!message.request) {
console.error(`Couldn't parse message ${JSON.stringify(message)}. No 'request' field.`)
return false // Silently error
}
let ret = true
switch(message.request) {
case 'start-editing':
ret = execute(enableEdition)
break
case 'end-editing':
ret = execute(disableEdition)
break
case 'export-html':
ret = execute(exportTabHTMLToLink)
break
case 'query-current-tab-edition-status':
ret = execute(queryEditionStatus)
break
}
return ret
}
browser.runtime.onMessage.addListener(receiveMessage);