TagSpaces is an offline, open source, document manager with tagging support
adding page capturing capabilities to the chrome extension
uggrock55edeeb08067
diff --git a/data/chromelight/captureContent.js b/data/chromelight/captureContent.jsnew file mode 100644index 000000000..9e20059c1--- /dev/null+++ b/data/chromelight/captureContent.js@@ -0,0 +1,89 @@+function DOMtoString(document_root) {+ var html = '',+ node = document_root.firstChild;+ while (node) {+ switch (node.nodeType) {+ case Node.ELEMENT_NODE:+ html += node.outerHTML;+ break;+ case Node.TEXT_NODE:+ html += node.nodeValue;+ break;+ case Node.CDATA_SECTION_NODE:+ html += '<![CDATA[' + node.nodeValue + ']]>';+ break;+ case Node.COMMENT_NODE:+ html += '<!--' + node.nodeValue + '-->';+ break;+ case Node.DOCUMENT_TYPE_NODE:+ // (X)HTML documents are identified by public identifiers+ html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';+ break;+ }+ node = node.nextSibling;+ }+ return html;+}++function getSelectionHtml() {+ var html = "";+ if (typeof window.getSelection != "undefined") {+ var sel = window.getSelection();+ if (sel.rangeCount) {+ var container = document.createElement("div");+ for (var i = 0, len = sel.rangeCount; i < len; ++i) {+ container.appendChild(sel.getRangeAt(i).cloneContents());+ }+ html = container.innerHTML;+ }+ } else if (typeof document.selection != "undefined") {+ if (document.selection.type == "Text") {+ html = document.selection.createRange().htmlText;+ }+ }+ return html;+}++chrome.extension.sendMessage({+ action: "getSource",+ //source: DOMtoString(document)+ source: getSelectionHtml()+});++/*+ function adjustRange(range) {+ range = range.cloneRange();++ // Expand range to encompass complete element if element's text+ // is completely selected by the range+ var container = range.commonAncestorContainer;+ var parentElement = container.nodeType == 3 ?+ container.parentNode : container;++ if (parentElement.textContent == range.toString()) {+ range.selectNode(parentElement);+ }++ return range;+ }++ function getSelectionHtml(selection) {+ var html = "", sel, range;+ if (typeof selection != "undefined") {+ sel = selection;+ if (sel.rangeCount) {+ var container = document.createElement("div");+ for (var i = 0, len = sel.rangeCount; i < len; ++i) {+ range = adjustRange( sel.getRangeAt(i) );+ container.appendChild(range.cloneContents());+ }+ html = container.innerHTML;+ }+ }+ //else if (typeof document.selection != "undefined") {+ // if (document.selection.type == "Text") {+ // html = document.selection.createRange().htmlText;+ // }+ //}+ return html;+ }*/\ No newline at end of filediff --git a/data/chromelight/chrome.api.js b/data/chromelight/chrome.api.jsindex 3d0cac37a..475d0cf52 100644--- a/data/chromelight/chrome.api.js+++ b/data/chromelight/chrome.api.js@@ -330,6 +330,13 @@TSPOSTIO.getFileProperties(fileProperties);};+ var saveSettings = function(content) {+ /*chrome.storage.sync.set({'tagSpacesSettings': content}, function() {+ // Notify that we saved.+ message('Settings saved');+ });*/+ };+// Bring the TagSpaces window on top of the windowsvar focusWindow = function() {window.focus();@@ -357,6 +364,7 @@exports.checkAccessFileURLAllowed = checkAccessFileURLAllowed;exports.checkNewVersion = checkNewVersion;exports.getFileProperties = getFileProperties;+ exports.saveSettings = saveSettings;exports.handleStartParameters = handleStartParameters;});diff --git a/data/chromelight/popup.js b/data/chromelight/popup.jsindex 7d7ea28e2..ea018af0c 100644--- a/data/chromelight/popup.js+++ b/data/chromelight/popup.js@@ -1,22 +1,177 @@-//document.ready = function() {- var startTS = document.getElementById("startTagSpaces");- startTS.onclick = function (e) {- chrome.tabs.create({url: '../index.html'});- };+/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+ * Use of this source code is governed by a AGPL3 license that+ * can be found in the LICENSE file. */- var saveAsMhtml = document.getElementById("saveAsMhtml");+'use strict';++(function() {+ console.log("Loading Popup...");var tags;- saveAsMhtml.onclick = function (e) {- chrome.tabs.getSelected(null, function(tab) {+ var html;+ var htmlTemplate;+ var tagLibrary;++ function init() {+ loadSettingsLocalStorage();++ $('#tags').select2('data', null);+ $("#tags").select2({+ multiple: true,+ tags: extractAllTags(tagLibrary),+ tokenSeparators: [","," "],+ minimumInputLength: 2,+ selectOnBlur: true+ });++ $("#startTagSpaces").on("click", function (e) {+ chrome.tabs.create({url: '../index.html'});+ });++ $("#saveAsMhtml").on('click', saveAsMHTML);++ $("#saveSelectionAsHtml").on("click", function () {+ chrome.tabs.executeScript(null, {+ file: "chromelight/captureContent.js"+ }, function () {+ if (chrome.extension.lastError) {+ console.log('There was an error injecting script : \n' + chrome.extension.lastError.message);+ }+ });+ });++ $("#saveScreenshot").on("click", saveScreenshot);++ chrome.extension.onMessage.addListener(function (request, sender) {+ if (request.action == "getSource") {+ chrome.tabs.getSelected(null, function (tab) {+ //console.log("HTML: " + request.source);+ var cleanenHTML = prepareContent(request.source);+ var htmlBlob = new Blob([cleanenHTML], {type: "text/html;charset=utf-8"});+ tags = document.getElementById("tags").value;+ if (tags) {+ tags = tags.split(",").join(" ");+ saveAs(htmlBlob, tab.title + ' [' + tags + '].html');+ } else {+ saveAs(htmlBlob, tab.title + '.html');+ }+ });+ }+ });+ }++ function saveAsMHTML() {+ chrome.tabs.getSelected(null, function (tab) {tags = document.getElementById("tags").value;chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml) {- if(tags) {+ if (tags) {+ tags = tags.split(",").join(" ");+ saveAs(mhtml, tab.title + ' [' + tags + '].mhtml');+ } else {+ saveAs(mhtml, tab.title + '.mhtml');+ }+ });+ });+ }++ function saveScreenshot() {+ chrome.tabs.getSelected(null, function (tab) {+ tags = document.getElementById("tags").value;+ chrome.tabs.captureVisibleTab(null, {"format": "png"}, function (image) {+ console.log("Screenshot: " + image);+ if (tags) {tags = tags.split(",").join(" ");- saveAs(mhtml, tab.title +' ['+tags+'].mhtml');+ saveAs(dataURItoBlob(image), tab.title + ' [' + tags + '].png');} else {- saveAs(mhtml, tab.title + '.mhtml');+ saveAs(dataURItoBlob(image), tab.title + '.png');}});});- };-//}\ No newline at end of file+ }++ function dataURItoBlob(dataURI) {+ // convert base64 to raw binary data held in a string+ var byteString = atob(dataURI.split(',')[1]);++ // separate out the mime component+ var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];++ // write the bytes of the string to an ArrayBuffer+ var arrayBuffer = new ArrayBuffer(byteString.length);+ var _ia = new Uint8Array(arrayBuffer);+ for (var i = 0; i < byteString.length; i++) {+ _ia[i] = byteString.charCodeAt(i);+ }++ var dataView = new DataView(arrayBuffer);+ var blob = new Blob([dataView], {type: mimeString});+ return blob;+ }++ function getBase64Image(imgURL) {+ var canvas = document.createElement("canvas");+ var img = new Image();+ img.src = imgURL;+ canvas.width = img.width;+ canvas.height = img.height;+ var ctx = canvas.getContext("2d");+ ctx.drawImage(img, 0, 0);+ return canvas.toDataURL("image/png");+ }++ function prepareContent(uncleanedHTML) {+ console.log("uncleaned "+uncleanedHTML);+ var cleanedHTML = DOMPurify.sanitize(uncleanedHTML);++ console.log("cleaned "+cleanedHTML);+ // saving all images as png in base64 format+ var match,+ urls = [],+ imgUrl = "",+ rex = /<img.*?src="([^">]*\/([^">]*?))".*?>/g;++ while ( match = rex.exec( cleanedHTML ) ) {+ imgUrl = match[1];+ //console.log("URLs: "+imgUrl);+ urls.push([imgUrl, getBase64Image(imgUrl)]);+ }++ urls.forEach(function(dataURLObject) {+ cleanedHTML = cleanedHTML.split(dataURLObject[0]).join(dataURLObject[1]);+ //console.log(dataURLObject[0]+" - "+dataURLObject[1]);+ });+ // end saving all images++ cleanedHTML = "<body>"+cleanedHTML+"</body>";+ cleanedHTML = htmlTemplate.replace(/\<body[^>]*\>([^]*)\<\/body>/m,cleanedHTML);+ return cleanedHTML;+ }++ function loadSettingsLocalStorage() {+ try {+ var settings = JSON.parse(localStorage.getItem('tagSpacesSettings'));+ //console.log("Settings: "+JSON.stringify(tmpSettings));+ if(settings !== null) {+ htmlTemplate = settings.newHTMLFileContent;+ tagLibrary = settings.tagGroups;+ }+ console.log("Loaded settings from local storage: "+JSON.stringify(tagLibrary));+ } catch(ex) {+ console.log("Loading settings from local storage failed due exception: "+ex);+ }+ }++ function extractAllTags() {+ var allTags = [];+ for(var i=0; i < tagLibrary.length; i++) {+ for(var j=0; j < tagLibrary[i].children.length; j++) {+ if(tagLibrary[i].children[j].type === "plain") {+ allTags.push(tagLibrary[i].children[j].title);+ }+ }+ }+ return allTags;+ }++ $(document).ready(init);++}());\ No newline at end of filediff --git a/data/popup.html b/data/popup.htmlindex d95db9a8e..f710812a2 100644--- a/data/popup.html+++ b/data/popup.html@@ -15,19 +15,22 @@ can be found in the LICENSE file.<link rel="stylesheet" type="text/css" href="assets/tagspaces.css"><!--script type="text/javascript" data-main="loader" src="libs/requirejs/require.js"></script--></head>-<body style="width: 300px; height: 320px; padding:0; font-size: 14px;">-<div class="well">+<body style="width: 520px; height: 300px; padding:0; font-size: 14px;">+<div class="well" style="margin: 0;"><a href="#" class="btn btn-primary" id="startTagSpaces" style="width: 100%;"><img src="assets/icon128.png" style="max-height: 32px; max-width: 32px;"/> Start TagSpaces</a><form role="form" data-toggle="validator" style="margin-top: 20px;"><div class="form-group">- <label class="control-label" for="tags" data-i18n="ns.dialogs:tagOperationTag">Tags</label>+ <label class="control-label" for="tags" data-i18n="ns.dialogs:tagOperationTag">1. Tags</label><input class="form-control" type="text" name="tags" id="tags" autocomplete="off"data-i18n="[placeholder]ns.dialogs:tagOperationTagsPlaceholder"/><p class="help-block" data-i18n="ns.dialogs:editTagNamesRestrictionsHelp">Tags should have a minimum length of 2 characters and should not contain special characters such as spaces, #, / ,\ and other.</p></div></form>- <div class="btn-toolbar text-center">- <a href="#" class="btn btn-primary" id="saveAsMhtml">Save current page as MHTML</a><br>+ <label>2. Action</label>+ <div class="btn-toolbar text-center noWrap">+ <a href="#" class="btn btn-primary" id="saveAsMhtml" title="Save whole page as MHTML"><i class="fa fa-file fa-lg fa-fw"></i> <span>Save Whole Page</span></a>+ <a href="#" class="btn btn-primary" id="saveSelectionAsHtml" title="Save selected content as HTML"><i class="fa fa-file-text fa-lg fa-fw"></i> <span>Save Selected</span></a>+ <a href="#" class="btn btn-primary" id="saveScreenshot" title="Save screenshot as PNG"><i class="fa fa-camera fa-lg fa-fw"></i> <span>Screenshot</span></a></div></div><script type="text/javascript" src="libs/jquery/jquery-2.1.1.min.js"></script>@@ -35,7 +38,7 @@ can be found in the LICENSE file.<script type="text/javascript" src="libs/filesaver.js/FileSaver.js"></script><script type="text/javascript" src="libs/i18next/i18next.amd.withJQuery-1.7.2.min.js"></script><script type="text/javascript" src="libs/select2/select2.min.js"></script>-<!--script type="text/javascript" src="chromelight/chrome.api.js"></script-->+<script type="text/javascript" src="libs/dompurify/purify.js"></script><script type="text/javascript" src="chromelight/popup.js"></script></body></html>\ No newline at end of file