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:
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "DocuElevate - Send to Document Processor",
|
||||
"version": "1.0.0",
|
||||
"description": "Send files from your browser directly to DocuElevate for processing",
|
||||
"version": "1.1.0",
|
||||
"description": "Send files or clip web pages from your browser directly to DocuElevate for processing",
|
||||
"permissions": [
|
||||
"activeTab",
|
||||
"storage",
|
||||
"contextMenus",
|
||||
"notifications"
|
||||
"notifications",
|
||||
"scripting"
|
||||
],
|
||||
"host_permissions": [],
|
||||
"host_permissions": ["<all_urls>"],
|
||||
"action": {
|
||||
"default_popup": "popup/popup.html",
|
||||
"default_icon": {
|
||||
|
||||
@@ -127,6 +127,35 @@ small {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
|
||||
.mode-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.btn-mode {
|
||||
flex: 1;
|
||||
background-color: #e9ecef;
|
||||
color: #495057;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.btn-mode:hover {
|
||||
background-color: #dee2e6;
|
||||
}
|
||||
|
||||
.btn-mode.active {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.clip-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.info-box {
|
||||
background-color: #e7f3ff;
|
||||
border: 1px solid #b3d9ff;
|
||||
|
||||
@@ -27,8 +27,16 @@
|
||||
<button id="save-config" class="btn btn-primary">Save Configuration</button>
|
||||
</div>
|
||||
|
||||
<div id="mode-section" class="section hidden">
|
||||
<h2>Select Mode</h2>
|
||||
<div class="mode-buttons">
|
||||
<button id="mode-url" class="btn btn-mode active">Send URL</button>
|
||||
<button id="mode-clip" class="btn btn-mode">Clip Page</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="send-section" class="section hidden">
|
||||
<h2>Send File to DocuElevate</h2>
|
||||
<h2>Send URL to DocuElevate</h2>
|
||||
<div class="info-box">
|
||||
<p><strong>Current URL:</strong></p>
|
||||
<p id="current-url" class="url-display"></p>
|
||||
@@ -41,6 +49,24 @@
|
||||
<button id="show-config" class="btn btn-secondary">Change Settings</button>
|
||||
</div>
|
||||
|
||||
<div id="clip-section" class="section hidden">
|
||||
<h2>Clip Web Page</h2>
|
||||
<div class="info-box">
|
||||
<p><strong>Page Title:</strong></p>
|
||||
<p id="page-title" class="url-display"></p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clip-filename">Filename (optional):</label>
|
||||
<input type="text" id="clip-filename" placeholder="Leave blank to use page title">
|
||||
<small>Will be saved as PDF</small>
|
||||
</div>
|
||||
<div class="clip-buttons">
|
||||
<button id="clip-full-page" class="btn btn-primary">Clip Full Page</button>
|
||||
<button id="clip-selection" class="btn btn-primary">Clip Selection</button>
|
||||
</div>
|
||||
<button id="show-config-from-clip" class="btn btn-secondary">Change Settings</button>
|
||||
</div>
|
||||
|
||||
<div id="status-section" class="section hidden">
|
||||
<div id="status-message"></div>
|
||||
</div>
|
||||
|
||||
@@ -2,18 +2,29 @@
|
||||
|
||||
// DOM elements
|
||||
const configSection = document.getElementById('config-section');
|
||||
const modeSection = document.getElementById('mode-section');
|
||||
const sendSection = document.getElementById('send-section');
|
||||
const clipSection = document.getElementById('clip-section');
|
||||
const statusSection = document.getElementById('status-section');
|
||||
const statusMessage = document.getElementById('status-message');
|
||||
|
||||
const serverUrlInput = document.getElementById('server-url');
|
||||
const sessionCookieInput = document.getElementById('session-cookie');
|
||||
const filenameInput = document.getElementById('filename');
|
||||
const clipFilenameInput = document.getElementById('clip-filename');
|
||||
const currentUrlDisplay = document.getElementById('current-url');
|
||||
const pageTitleDisplay = document.getElementById('page-title');
|
||||
|
||||
const saveConfigBtn = document.getElementById('save-config');
|
||||
const sendFileBtn = document.getElementById('send-file');
|
||||
const showConfigBtn = document.getElementById('show-config');
|
||||
const showConfigFromClipBtn = document.getElementById('show-config-from-clip');
|
||||
const modeUrlBtn = document.getElementById('mode-url');
|
||||
const modeClipBtn = document.getElementById('mode-clip');
|
||||
const clipFullPageBtn = document.getElementById('clip-full-page');
|
||||
const clipSelectionBtn = document.getElementById('clip-selection');
|
||||
|
||||
let currentMode = 'url'; // 'url' or 'clip'
|
||||
|
||||
// Load configuration and current tab URL on popup open
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
@@ -28,14 +39,17 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
sessionCookieInput.value = config.sessionCookie;
|
||||
}
|
||||
|
||||
// Get current tab URL
|
||||
// Get current tab info
|
||||
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
const currentUrl = tabs[0]?.url || '';
|
||||
const pageTitle = tabs[0]?.title || '';
|
||||
currentUrlDisplay.textContent = currentUrl;
|
||||
pageTitleDisplay.textContent = pageTitle;
|
||||
|
||||
// Show appropriate section
|
||||
if (config.serverUrl) {
|
||||
showSendSection();
|
||||
showModeSection();
|
||||
showUrlMode();
|
||||
} else {
|
||||
showConfigSection();
|
||||
}
|
||||
@@ -67,11 +81,21 @@ saveConfigBtn.addEventListener('click', async () => {
|
||||
showStatus('Configuration saved successfully!', 'success');
|
||||
|
||||
setTimeout(() => {
|
||||
showSendSection();
|
||||
showModeSection();
|
||||
showUrlMode();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// Send file to DocuElevate
|
||||
// Mode selection
|
||||
modeUrlBtn.addEventListener('click', () => {
|
||||
showUrlMode();
|
||||
});
|
||||
|
||||
modeClipBtn.addEventListener('click', () => {
|
||||
showClipMode();
|
||||
});
|
||||
|
||||
// Send file URL to DocuElevate
|
||||
sendFileBtn.addEventListener('click', async () => {
|
||||
const config = await loadConfig();
|
||||
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
@@ -85,7 +109,7 @@ sendFileBtn.addEventListener('click', async () => {
|
||||
// Disable button and show loading
|
||||
sendFileBtn.disabled = true;
|
||||
sendFileBtn.classList.add('loading');
|
||||
showStatus('Sending file to DocuElevate...', 'info');
|
||||
showStatus('Sending URL to DocuElevate...', 'info');
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
@@ -112,12 +136,12 @@ sendFileBtn.addEventListener('click', async () => {
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
showStatus(
|
||||
`✓ File sent successfully! Task ID: ${result.task_id}\nFilename: ${result.filename}`,
|
||||
`✓ URL sent successfully! Task ID: ${result.task_id}\nFilename: ${result.filename}`,
|
||||
'success'
|
||||
);
|
||||
} else {
|
||||
// Try to parse JSON error, fall back to status text
|
||||
let errorMessage = 'Failed to send file';
|
||||
let errorMessage = 'Failed to send URL';
|
||||
try {
|
||||
const result = await response.json();
|
||||
errorMessage = result.detail || errorMessage;
|
||||
@@ -138,21 +162,188 @@ sendFileBtn.addEventListener('click', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Clip full page
|
||||
clipFullPageBtn.addEventListener('click', async () => {
|
||||
await handleClipPage('full');
|
||||
});
|
||||
|
||||
// Clip selection
|
||||
clipSelectionBtn.addEventListener('click', async () => {
|
||||
await handleClipPage('selection');
|
||||
});
|
||||
|
||||
// Handle clipping page
|
||||
async function handleClipPage(mode) {
|
||||
const config = await loadConfig();
|
||||
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
const tab = tabs[0];
|
||||
|
||||
if (!tab) {
|
||||
showStatus('No active tab found', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable buttons and show loading
|
||||
const button = mode === 'full' ? clipFullPageBtn : clipSelectionBtn;
|
||||
button.disabled = true;
|
||||
button.classList.add('loading');
|
||||
showStatus(`Clipping ${mode === 'full' ? 'full page' : 'selection'}...`, 'info');
|
||||
|
||||
try {
|
||||
// Capture page content using content script
|
||||
let captureFunc;
|
||||
if (mode === 'full') {
|
||||
captureFunc = () => {
|
||||
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
|
||||
};
|
||||
};
|
||||
} else {
|
||||
captureFunc = () => {
|
||||
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
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
func: captureFunc
|
||||
});
|
||||
|
||||
if (!result || !result.result) {
|
||||
throw new Error('Failed to capture page content');
|
||||
}
|
||||
|
||||
const pageData = result.result;
|
||||
|
||||
// Send message to background script to convert and upload
|
||||
const response = await chrome.runtime.sendMessage({
|
||||
type: 'CLIP_PAGE',
|
||||
data: {
|
||||
html: pageData.html,
|
||||
title: pageData.title,
|
||||
filename: clipFilenameInput.value.trim() || pageData.title,
|
||||
serverUrl: config.serverUrl,
|
||||
sessionCookie: config.sessionCookie
|
||||
}
|
||||
});
|
||||
|
||||
if (response.success) {
|
||||
showStatus(
|
||||
`✓ Page clipped successfully! Task ID: ${response.data.task_id}`,
|
||||
'success'
|
||||
);
|
||||
} else {
|
||||
throw new Error(response.error || 'Failed to clip page');
|
||||
}
|
||||
} catch (error) {
|
||||
showStatus(
|
||||
`Error: ${error.message || 'Failed to clip page'}`,
|
||||
'error'
|
||||
);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.classList.remove('loading');
|
||||
}
|
||||
}
|
||||
|
||||
// Show configuration section
|
||||
showConfigBtn.addEventListener('click', () => {
|
||||
showConfigSection();
|
||||
});
|
||||
|
||||
showConfigFromClipBtn.addEventListener('click', () => {
|
||||
showConfigSection();
|
||||
});
|
||||
|
||||
// Utility functions
|
||||
function showConfigSection() {
|
||||
configSection.classList.remove('hidden');
|
||||
modeSection.classList.add('hidden');
|
||||
sendSection.classList.add('hidden');
|
||||
clipSection.classList.add('hidden');
|
||||
statusSection.classList.add('hidden');
|
||||
}
|
||||
|
||||
function showSendSection() {
|
||||
function showModeSection() {
|
||||
configSection.classList.add('hidden');
|
||||
modeSection.classList.remove('hidden');
|
||||
statusSection.classList.add('hidden');
|
||||
}
|
||||
|
||||
function showUrlMode() {
|
||||
currentMode = 'url';
|
||||
modeUrlBtn.classList.add('active');
|
||||
modeClipBtn.classList.remove('active');
|
||||
sendSection.classList.remove('hidden');
|
||||
clipSection.classList.add('hidden');
|
||||
statusSection.classList.add('hidden');
|
||||
}
|
||||
|
||||
function showClipMode() {
|
||||
currentMode = 'clip';
|
||||
modeClipBtn.classList.add('active');
|
||||
modeUrlBtn.classList.remove('active');
|
||||
clipSection.classList.remove('hidden');
|
||||
sendSection.classList.add('hidden');
|
||||
statusSection.classList.add('hidden');
|
||||
}
|
||||
|
||||
|
||||
@@ -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,12 +83,99 @@ 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) => {
|
||||
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);
|
||||
@@ -81,6 +187,10 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (info.menuItemId === 'send-to-docuelevate') {
|
||||
// Get the URL to send (link URL or page URL)
|
||||
const targetUrl = info.linkUrl || info.pageUrl;
|
||||
|
||||
// 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}`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// Web page capture script for DocuElevate browser extension
|
||||
// This script handles capturing web page content for PDF conversion
|
||||
|
||||
/**
|
||||
* Capture the full page HTML with inline styles
|
||||
* @returns {Object} Page data with HTML, title, and URL
|
||||
*/
|
||||
function captureFullPage() {
|
||||
// Clone the document to avoid modifying the original
|
||||
const clonedDoc = document.cloneNode(true);
|
||||
|
||||
// Get all stylesheets and inline them
|
||||
const styles = Array.from(document.styleSheets)
|
||||
.map(sheet => {
|
||||
try {
|
||||
return Array.from(sheet.cssRules)
|
||||
.map(rule => rule.cssText)
|
||||
.join('\n');
|
||||
} catch (e) {
|
||||
// Handle CORS issues with external stylesheets
|
||||
console.warn('Could not access stylesheet:', sheet.href, e);
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
// Get page HTML
|
||||
const html = document.documentElement.outerHTML;
|
||||
|
||||
// Create a complete HTML document with inlined styles
|
||||
const styledHtml = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>${document.title}</title>
|
||||
<style>${styles}</style>
|
||||
</head>
|
||||
<body>
|
||||
${document.body.innerHTML}
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
return {
|
||||
html: styledHtml,
|
||||
title: document.title,
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture selected content from the page
|
||||
* @returns {Object} Selection data with HTML, text, and metadata
|
||||
*/
|
||||
function 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());
|
||||
|
||||
// Get computed styles for the selection
|
||||
const styles = [];
|
||||
const elements = container.querySelectorAll('*');
|
||||
elements.forEach(el => {
|
||||
const computed = window.getComputedStyle(el);
|
||||
// Only preserve essential styles
|
||||
const essentialStyles = [
|
||||
'font-family', 'font-size', 'font-weight', 'color',
|
||||
'background-color', 'text-align', 'margin', 'padding'
|
||||
];
|
||||
let styleStr = '';
|
||||
essentialStyles.forEach(prop => {
|
||||
const value = computed.getPropertyValue(prop);
|
||||
if (value) {
|
||||
styleStr += `${prop}: ${value}; `;
|
||||
}
|
||||
});
|
||||
if (styleStr) {
|
||||
el.setAttribute('style', styleStr);
|
||||
}
|
||||
});
|
||||
|
||||
const 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>
|
||||
`;
|
||||
|
||||
return {
|
||||
html: html,
|
||||
text: selection.toString(),
|
||||
title: document.title + ' - Selection',
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Take a screenshot of the visible viewport
|
||||
* @returns {Promise<string>} Data URL of the screenshot
|
||||
*/
|
||||
async function captureScreenshot() {
|
||||
// This will be called from the background script
|
||||
// since content scripts can't use chrome.tabs.captureVisibleTab
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage(
|
||||
{ type: 'CAPTURE_SCREENSHOT' },
|
||||
response => {
|
||||
if (response.success) {
|
||||
resolve(response.dataUrl);
|
||||
} else {
|
||||
reject(new Error(response.error));
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for capture requests from popup or background
|
||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message.type === 'CAPTURE_FULL_PAGE') {
|
||||
try {
|
||||
const pageData = captureFullPage();
|
||||
sendResponse({ success: true, data: pageData });
|
||||
} catch (error) {
|
||||
sendResponse({ success: false, error: error.message });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message.type === 'CAPTURE_SELECTION') {
|
||||
try {
|
||||
const selectionData = captureSelection();
|
||||
sendResponse({ success: true, data: selectionData });
|
||||
} catch (error) {
|
||||
sendResponse({ success: false, error: error.message });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// Export functions for use in tests or other scripts
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = {
|
||||
captureFullPage,
|
||||
captureSelection
|
||||
};
|
||||
}
|
||||
@@ -3,9 +3,114 @@
|
||||
// This script runs on all web pages to enable communication
|
||||
// between page content and the extension
|
||||
|
||||
// Message handler reserved for future functionality
|
||||
// Future use case: Extract additional page metadata or interact with page content
|
||||
// Currently not used - can be removed if not needed
|
||||
/**
|
||||
* Capture the full page HTML with inline styles
|
||||
*/
|
||||
function captureFullPage() {
|
||||
// Get all stylesheets and inline them
|
||||
const styles = Array.from(document.styleSheets)
|
||||
.map(sheet => {
|
||||
try {
|
||||
return Array.from(sheet.cssRules)
|
||||
.map(rule => rule.cssText)
|
||||
.join('\n');
|
||||
} catch (e) {
|
||||
// Handle CORS issues with external stylesheets
|
||||
console.warn('Could not access stylesheet:', sheet.href, e);
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
// Create a complete HTML document with inlined styles
|
||||
const styledHtml = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>${document.title}</title>
|
||||
<style>${styles}</style>
|
||||
</head>
|
||||
<body>
|
||||
${document.body.innerHTML}
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
return {
|
||||
html: styledHtml,
|
||||
title: document.title,
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture selected content from the page
|
||||
*/
|
||||
function 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());
|
||||
|
||||
// Get computed styles for the selection
|
||||
const elements = container.querySelectorAll('*');
|
||||
elements.forEach(el => {
|
||||
const computed = window.getComputedStyle(el);
|
||||
// Only preserve essential styles
|
||||
const essentialStyles = [
|
||||
'font-family', 'font-size', 'font-weight', 'color',
|
||||
'background-color', 'text-align', 'margin', 'padding'
|
||||
];
|
||||
let styleStr = '';
|
||||
essentialStyles.forEach(prop => {
|
||||
const value = computed.getPropertyValue(prop);
|
||||
if (value) {
|
||||
styleStr += `${prop}: ${value}; `;
|
||||
}
|
||||
});
|
||||
if (styleStr) {
|
||||
el.setAttribute('style', styleStr);
|
||||
}
|
||||
});
|
||||
|
||||
const 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>`;
|
||||
|
||||
return {
|
||||
html: html,
|
||||
text: selection.toString(),
|
||||
title: document.title + ' - Selection',
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
// Message handler
|
||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message.type === 'GET_PAGE_INFO') {
|
||||
// Return information about the current page
|
||||
@@ -15,6 +120,26 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
};
|
||||
sendResponse(pageInfo);
|
||||
}
|
||||
|
||||
if (message.type === 'CAPTURE_FULL_PAGE') {
|
||||
try {
|
||||
const pageData = captureFullPage();
|
||||
sendResponse({ success: true, data: pageData });
|
||||
} catch (error) {
|
||||
sendResponse({ success: false, error: error.message });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message.type === 'CAPTURE_SELECTION') {
|
||||
try {
|
||||
const selectionData = captureSelection();
|
||||
sendResponse({ success: true, data: selectionData });
|
||||
} catch (error) {
|
||||
sendResponse({ success: false, error: error.message });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// Detect if current page is a direct file link
|
||||
|
||||
Reference in New Issue
Block a user