feat(browser-extension): add web page clipping functionality
- Updated manifest to v1.1.0 with additional permissions (scripting, host_permissions) - Added web clipping context menu items (Clip Full Page, Clip Selection) - Enhanced background.js with PDF conversion using Chrome's printToPDF API - Updated content.js to capture full page HTML and selected content - Added new capture.js script for page capture utilities - Enhanced popup UI with mode toggle between "Send URL" and "Clip Page" - Added support for clipping full pages or selected content to PDF - Updated CSS for new mode buttons and clip section layout Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
@@ -10,12 +10,24 @@ chrome.runtime.onInstalled.addListener((details) => {
|
||||
console.log('DocuElevate extension updated');
|
||||
}
|
||||
|
||||
// Create context menu item
|
||||
// Create context menu items
|
||||
chrome.contextMenus.create({
|
||||
id: 'send-to-docuelevate',
|
||||
title: 'Send to DocuElevate',
|
||||
title: 'Send URL to DocuElevate',
|
||||
contexts: ['link', 'page']
|
||||
});
|
||||
|
||||
chrome.contextMenus.create({
|
||||
id: 'clip-page-to-docuelevate',
|
||||
title: 'Clip Full Page to DocuElevate',
|
||||
contexts: ['page']
|
||||
});
|
||||
|
||||
chrome.contextMenus.create({
|
||||
id: 'clip-selection-to-docuelevate',
|
||||
title: 'Clip Selection to DocuElevate',
|
||||
contexts: ['selection']
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for messages from content script or popup
|
||||
@@ -26,6 +38,13 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
.catch(error => sendResponse({ success: false, error: error.message }));
|
||||
return true; // Keep channel open for async response
|
||||
}
|
||||
|
||||
if (message.type === 'CLIP_PAGE') {
|
||||
handleClipPage(message.data)
|
||||
.then(result => sendResponse({ success: true, data: result }))
|
||||
.catch(error => sendResponse({ success: false, error: error.message }));
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// Handle sending URL to DocuElevate
|
||||
@@ -64,23 +83,114 @@ async function handleSendUrl(data) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
// Handle clipping page content to DocuElevate
|
||||
async function handleClipPage(data) {
|
||||
const { html, title, filename, serverUrl, sessionCookie } = data;
|
||||
|
||||
if (!html || !serverUrl) {
|
||||
throw new Error('HTML content and server URL are required');
|
||||
}
|
||||
|
||||
// Convert HTML to PDF using browser's print API
|
||||
let pdfData;
|
||||
try {
|
||||
pdfData = await convertHtmlToPdf(html);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to convert to PDF: ${error.message}`);
|
||||
}
|
||||
|
||||
const headers = {};
|
||||
if (sessionCookie) {
|
||||
headers['Cookie'] = sessionCookie;
|
||||
}
|
||||
|
||||
// Determine filename
|
||||
const safeFilename = filename || title || 'web-clip';
|
||||
const pdfFilename = safeFilename.endsWith('.pdf') ? safeFilename : `${safeFilename}.pdf`;
|
||||
|
||||
// Create form data with PDF
|
||||
const formData = new FormData();
|
||||
const blob = new Blob([pdfData], { type: 'application/pdf' });
|
||||
formData.append('file', blob, pdfFilename);
|
||||
|
||||
const response = await fetch(`${serverUrl}/api/files/upload`, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: formData,
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ detail: 'Unknown error' }));
|
||||
throw new Error(errorData.detail || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert HTML to PDF using Chrome's printing API
|
||||
* @param {string} html - HTML content to convert
|
||||
* @returns {Promise<Uint8Array>} PDF data
|
||||
*/
|
||||
async function convertHtmlToPdf(html) {
|
||||
// Create a data URL with the HTML content
|
||||
const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
|
||||
|
||||
// Create a new tab with the HTML
|
||||
const tab = await chrome.tabs.create({ url: dataUrl, active: false });
|
||||
|
||||
try {
|
||||
// Wait for the page to load
|
||||
await new Promise(resolve => {
|
||||
const listener = (tabId, changeInfo) => {
|
||||
if (tabId === tab.id && changeInfo.status === 'complete') {
|
||||
chrome.tabs.onUpdated.removeListener(listener);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
chrome.tabs.onUpdated.addListener(listener);
|
||||
});
|
||||
|
||||
// Give it a bit more time to render
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
// Use Chrome's print to PDF API
|
||||
const pdfData = await chrome.tabs.printToPDF(tab.id, {
|
||||
paperFormat: 'A4',
|
||||
landscape: false,
|
||||
marginTop: 0.4,
|
||||
marginBottom: 0.4,
|
||||
marginLeft: 0.4,
|
||||
marginRight: 0.4,
|
||||
printBackground: true,
|
||||
preferCSSPageSize: false
|
||||
});
|
||||
|
||||
return new Uint8Array(pdfData);
|
||||
} finally {
|
||||
// Close the temporary tab
|
||||
await chrome.tabs.remove(tab.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle context menu clicks
|
||||
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
// Load configuration
|
||||
const config = await new Promise((resolve) => {
|
||||
chrome.storage.sync.get(['serverUrl', 'sessionCookie'], resolve);
|
||||
});
|
||||
|
||||
if (!config.serverUrl) {
|
||||
// Open popup to configure
|
||||
chrome.action.openPopup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (info.menuItemId === 'send-to-docuelevate') {
|
||||
// Get the URL to send (link URL or page URL)
|
||||
const targetUrl = info.linkUrl || info.pageUrl;
|
||||
|
||||
// Load configuration
|
||||
const config = await new Promise((resolve) => {
|
||||
chrome.storage.sync.get(['serverUrl', 'sessionCookie'], resolve);
|
||||
});
|
||||
|
||||
if (!config.serverUrl) {
|
||||
// Open popup to configure
|
||||
chrome.action.openPopup();
|
||||
return;
|
||||
}
|
||||
|
||||
// Send the URL
|
||||
try {
|
||||
const result = await handleSendUrl({
|
||||
@@ -94,7 +204,7 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate',
|
||||
message: `File sent successfully! Task ID: ${result.task_id}`
|
||||
message: `URL sent successfully! Task ID: ${result.task_id}`
|
||||
});
|
||||
} catch (error) {
|
||||
// Show error notification
|
||||
@@ -102,7 +212,150 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate Error',
|
||||
message: `Failed to send file: ${error.message}`
|
||||
message: `Failed to send URL: ${error.message}`
|
||||
});
|
||||
}
|
||||
} else if (info.menuItemId === 'clip-page-to-docuelevate') {
|
||||
// Capture full page
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
func: () => {
|
||||
// This function runs in the page context
|
||||
const captureFullPage = () => {
|
||||
const styles = Array.from(document.styleSheets)
|
||||
.map(sheet => {
|
||||
try {
|
||||
return Array.from(sheet.cssRules)
|
||||
.map(rule => rule.cssText)
|
||||
.join('\n');
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
return {
|
||||
html: `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>${document.title}</title>
|
||||
<style>${styles}</style>
|
||||
</head>
|
||||
<body>
|
||||
${document.body.innerHTML}
|
||||
</body>
|
||||
</html>`,
|
||||
title: document.title,
|
||||
url: window.location.href
|
||||
};
|
||||
};
|
||||
return captureFullPage();
|
||||
}
|
||||
});
|
||||
|
||||
const pageData = result.result;
|
||||
|
||||
// Send to DocuElevate
|
||||
const uploadResult = await handleClipPage({
|
||||
html: pageData.html,
|
||||
title: pageData.title,
|
||||
filename: `${pageData.title}.pdf`,
|
||||
serverUrl: config.serverUrl,
|
||||
sessionCookie: config.sessionCookie
|
||||
});
|
||||
|
||||
// Show success notification
|
||||
chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate',
|
||||
message: `Page clipped successfully! Task ID: ${uploadResult.task_id}`
|
||||
});
|
||||
} catch (error) {
|
||||
// Show error notification
|
||||
chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate Error',
|
||||
message: `Failed to clip page: ${error.message}`
|
||||
});
|
||||
}
|
||||
} else if (info.menuItemId === 'clip-selection-to-docuelevate') {
|
||||
// Capture selection
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
func: () => {
|
||||
// This function runs in the page context
|
||||
const captureSelection = () => {
|
||||
const selection = window.getSelection();
|
||||
|
||||
if (!selection || selection.rangeCount === 0) {
|
||||
throw new Error('No content selected');
|
||||
}
|
||||
|
||||
const range = selection.getRangeAt(0);
|
||||
const container = document.createElement('div');
|
||||
container.appendChild(range.cloneContents());
|
||||
|
||||
return {
|
||||
html: `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>${document.title} - Selection</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>${document.title}</h1>
|
||||
<p><small>Source: ${window.location.href}</small></p>
|
||||
<hr>
|
||||
${container.innerHTML}
|
||||
</body>
|
||||
</html>`,
|
||||
title: document.title + ' - Selection',
|
||||
url: window.location.href
|
||||
};
|
||||
};
|
||||
return captureSelection();
|
||||
}
|
||||
});
|
||||
|
||||
const selectionData = result.result;
|
||||
|
||||
// Send to DocuElevate
|
||||
const uploadResult = await handleClipPage({
|
||||
html: selectionData.html,
|
||||
title: selectionData.title,
|
||||
filename: `${selectionData.title}.pdf`,
|
||||
serverUrl: config.serverUrl,
|
||||
sessionCookie: config.sessionCookie
|
||||
});
|
||||
|
||||
// Show success notification
|
||||
chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate',
|
||||
message: `Selection clipped successfully! Task ID: ${uploadResult.task_id}`
|
||||
});
|
||||
} catch (error) {
|
||||
// Show error notification
|
||||
chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon48.png',
|
||||
title: 'DocuElevate Error',
|
||||
message: `Failed to clip selection: ${error.message}`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user