Не подходит, ломает работу расширений. Например этого Link Text and Location Copier
Но мне подходит, с какого какие то веб сайты будут перезаписывать мне буфер обмена, нет уж у меня всегда отключена данная настройка.
А если понадобится подобное копирование как в расширении то можно и скрипт написать вместо расширения.
Отсутствует
Vitaliy V.как зарегистрировать в resource:// вот эту иконку?в том скрипте скажите пожалуйста
(async (id, url) => { if (location != url) return; var menuitem = document.createXULElement("menuitem"); document.getElementById(id).after(menuitem); var hidden = () => !nsContextMenu.contentData.context.linkTextStr; menuitem.hidden = true; menuitem.render = () => { if (hidden()) return; menuitem.hidden = false; menuitem.id = id + "text"; menuitem.label = "Скопировать текст ссылки"; menuitem.setAttribute("oncommand", "navigator.clipboard.writeText(gContextMenu.linkTextStr);"); delete menuitem.render; menuitem.className = "menuitem-iconic"; menuitem.image = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(142, 142, 152);fill-opacity:context-fill-opacity'><path d='M4.715 6.542 3.343 7.914a3 3 0 1 0 4.243 4.243l1.828-1.829A3 3 0 0 0 8.586 5.5L8 6.086a1.002 1.002 0 0 0-.154.199 2 2 0 0 1 .861 3.337L6.88 11.45a2 2 0 1 1-2.83-2.83l.793-.792a4.018 4.018 0 0 1-.128-1.287z'/><path d='M6.586 4.672A3 3 0 0 0 7.414 9.5l.775-.776a2 2 0 0 1-.896-3.346L9.12 3.55a2 2 0 1 1 2.83 2.83l-.793.792c.112.42.155.855.128 1.287l1.372-1.372a3 3 0 1 0-4.243-4.243L6.586 4.672z'/></g></svg>"; menuitem.render(); menuitem.render = () => menuitem.hidden = hidden(); } })("context-copylink", "chrome://browser/content/browser.xhtml");
Отсутствует
ломает работу расширений
Тут ещё вопрос ломает ли, в этом расширении Link Text and Location Copier изменил в linktextlocationcopier.js
/* const code = 'copyToClipboard(' + JSON.stringify(outputtext) + ',' + clickedItem.outputAsHTML +');'; browser.tabs.executeScript({ code: 'typeof copyToClipboard === "function";', }).then((results) => { if (!results || results[0] !== true) { return browser.tabs.executeScript(tab.id, { file: 'clipboard-helper.js' }); } }).then(() => { return browser.tabs.executeScript(tab.id, { code }); }).catch((error) => { console.error('Failed to copy text: ' + error); }); */ const type = clickedItem.outputAsHTML ? "text/html" : "text/plain"; const blob = new Blob([outputtext], { type }); const data = [new ClipboardItem({ [type]: blob })]; navigator.clipboard.write(data);
egorsemenov06
(async ( id = "context-copylink", image = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(0, 142, 152);fill-opacity:context-fill-opacity'><path d='M4.715 6.542 3.343 7.914a3 3 0 1 0 4.243 4.243l1.828-1.829A3 3 0 0 0 8.586 5.5L8 6.086a1.002 1.002 0 0 0-.154.199 2 2 0 0 1 .861 3.337L6.88 11.45a2 2 0 1 1-2.83-2.83l.793-.792a4.018 4.018 0 0 1-.128-1.287z'/><path d='M6.586 4.672A3 3 0 0 0 7.414 9.5l.775-.776a2 2 0 0 1-.896-3.346L9.12 3.55a2 2 0 1 1 2.83 2.83l-.793.792c.112.42.155.855.128 1.287l1.372-1.372a3 3 0 1 0-4.243-4.243L6.586 4.672z'/></g></svg>", substitution = `ucf-${id.toLowerCase()}-img`, PHandler = Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler), ) => { if (!PHandler.hasSubstitution(substitution)) PHandler.setSubstitution(substitution, Services.io.newURI(image)); var menuitem = document.createXULElement("menuitem"); document.getElementById(id).after(menuitem); var hidden = () => !nsContextMenu.contentData.context.linkTextStr; menuitem.hidden = true; menuitem.render = () => { if (hidden()) return; menuitem.hidden = false; menuitem.id = `${id}text`; menuitem.label = "Скопировать текст ссылки"; menuitem.setAttribute("oncommand", "navigator.clipboard.writeText(gContextMenu.linkTextStr);"); delete menuitem.render; menuitem.className = "menuitem-iconic"; menuitem.style.cssText = `list-style-image:url("resource://${substitution}");-moz-context-properties:fill,fill-opacity;fill:currentColor;`; menuitem.render(); menuitem.render = () => menuitem.hidden = hidden(); } })();
Отредактировано Vitaliy V. (10-05-2024 02:18:16)
Отсутствует
egorsemenov06
скрытый текстВыделить кодКод:
(async ( id = "context-copylink", image = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(0, 142, 152);fill-opacity:context-fill-opacity'><path d='M4.715 6.542 3.343 7.914a3 3 0 1 0 4.243 4.243l1.828-1.829A3 3 0 0 0 8.586 5.5L8 6.086a1.002 1.002 0 0 0-.154.199 2 2 0 0 1 .861 3.337L6.88 11.45a2 2 0 1 1-2.83-2.83l.793-.792a4.018 4.018 0 0 1-.128-1.287z'/><path d='M6.586 4.672A3 3 0 0 0 7.414 9.5l.775-.776a2 2 0 0 1-.896-3.346L9.12 3.55a2 2 0 1 1 2.83 2.83l-.793.792c.112.42.155.855.128 1.287l1.372-1.372a3 3 0 1 0-4.243-4.243L6.586 4.672z'/></g></svg>", substitution = `ucf-${id.toLowerCase()}-img`, PHandler = Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler), ) => { if (!PHandler.hasSubstitution(substitution)) PHandler.setSubstitution(substitution, Services.io.newURI(image)); var menuitem = document.createXULElement("menuitem"); document.getElementById(id).after(menuitem); var hidden = () => !nsContextMenu.contentData.context.linkTextStr; menuitem.hidden = true; menuitem.render = () => { if (hidden()) return; menuitem.hidden = false; menuitem.id = `${id}text`; menuitem.label = "Скопировать текст ссылки"; menuitem.setAttribute("oncommand", "navigator.clipboard.writeText(gContextMenu.linkTextStr);"); delete menuitem.render; menuitem.className = "menuitem-iconic"; menuitem.style.cssText = `list-style-image:url("resource://${substitution}");-moz-context-properties:fill,fill-opacity;fill:currentColor;`; menuitem.render(); menuitem.render = () => menuitem.hidden = hidden(); } })();
СПАСИБО БОЛЬШОЕ!!!!!
Отсутствует
Проверял на
Да это работает только на пока
Но здесь же не нужно копировать изображения вроде достаточно будет navigator.clipboard.writeText(), попробуйте так
/* const code = 'copyToClipboard(' + JSON.stringify(outputtext) + ',' + clickedItem.outputAsHTML +');'; browser.tabs.executeScript({ code: 'typeof copyToClipboard === "function";', }).then((results) => { if (!results || results[0] !== true) { return browser.tabs.executeScript(tab.id, { file: 'clipboard-helper.js' }); } }).then(() => { return browser.tabs.executeScript(tab.id, { code }); }).catch((error) => { console.error('Failed to copy text: ' + error); }); */ navigator.clipboard.writeText(outputtext);
Отсутствует
как уменьшить высоту панели вкладок?
Почему в этой теме непонятно, ну да ладно
:@-moz-document url("chrome://browser/content/browser.xhtml") { :root { --tab-min-height: 26px !important; --tab-block-margin: 1px !important; } :root[uidensity="touch"] { /* мобильный режим */ --tab-min-height: 32px !important; } .tab-label-container { height: 1.75em !important; } .tab-label { line-height: 1.25em !important; height: 1.25em !important; margin-block: 0 !important; } .tab-secondary-label { margin-block: -.25em 0 !important; font-size: .75em !important; } .tab-icon-sound-label { line-height: 1.25em !important; height: 1.25em !important; margin-block: 0 !important; } }
Отсутствует
Почему в этой теме непонятно, ну да ладно
Спасибо. Не работает. Менял --tab-min-height: 20px !important;
Другие стили (цвет и размер шрифтов) из этого же файла работают.
Может я путь { path: "correct.css", type: "AGENT_SHEET"}, не туда прописыаю?
Отсутствует
Менял --tab-min-height: 20px
Так бы и сказали что нужно так сильно уменьшить
@-moz-document url("chrome://browser/content/browser.xhtml") { :root { --tab-min-height: 20px !important; --tab-block-margin: 0px !important; --tabs-navbar-shadow-size: 0px !important; --tab-border-radius: 4px !important; } :root[uidensity="touch"] { /* мобильный режим */ --tab-min-height: 32px !important; } .tab-background { border-end-start-radius: 0 !important; border-end-end-radius: 0 !important; } .tab-label-container { height: 1.5em !important; } .tab-label { line-height: 1.25em !important; height: 1.25em !important; margin-block: 0 !important; } .tab-secondary-label { margin-block: -.25em 0 !important; font-size: .75em !important; } .tab-icon-sound-label { line-height: 1.25em !important; height: 1.25em !important; margin-block: 0 !important; } .tab-close-button { width: 18px !important; height: 18px !important; padding: 3px !important; } }
Отсутствует
Так бы и сказали что нужно так сильно уменьшить
Vitaliy V. Спасибо. Теперь нормально. Прямо камень с души упал.
Извините, что отвлекаю по мелочам.
Отсутствует
Алексей У. пишетА где можно достать UserChromeFiles для Firefox 88?
Благодарю, установил - работает. Правда хочу отметить замеченный мной нюанс (вернее, недоработку). Когда в адресную строку вводится поисковый запрос, dropmarker заменяется кнопкой "Перейти" (есть такая настройка в скрипте); однако если вместо запроса вставляется готовая ссылка, dropmarker остается на месте, хотя так же должен заменяться кнопкой перехода. Было бы неплохо автору исправить это. И еще небольшой вопрос - можно ли убрать из персонализации кнопку перезапуска или хотя бы перекрасить ее в черный цвет (она красная и этим сильно выделяется из ряда остальных кнопок)?
Отсутствует
Vitaliy V. как зарегистрировать в resource:// эту иконку?скажите пожалуйста
// Google Translate в контекстном меню....... (this.googletranslate = { init(that) { var lc = navigator.lastClick = {}, w = null, xhtmlns = 'http://www.w3.org/1999/xhtml'; var mouseUp = (e) => { if (e.button) return; lc.X = e.screenX - mozInnerScreenX; lc.Y = e.screenY - mozInnerScreenY; }; gBrowser.tabpanels.addEventListener('mouseup', mouseUp, false); this.destructor = () => { gBrowser.tabpanels.removeEventListener('mouseup', mouseUp, false); if (w) w.closeWin(); }; that.unloadlisteners.push("googletranslate"); var createWindow = function(text, status, title, id, pos, size) { var win = window, doc = win.document, wId = 'ujs_window'+(id || ''); w = doc.getElementById(wId); var keyDown = function(e) {if (!e.shiftKey && !e.ctrlKey && !e.altKey && e.keyCode == 27)doc.getElementById(wId).closeWin();}; var mouseDown = function() {doc.getElementById(wId).closeWin();}; if (w) w.closeWin(); w = doc.createElementNS(xhtmlns, 'div'); w.setAttribute('style', 'position:fixed;display:block;visibility:hidden;left:0;top:0;width:auto;height:auto;border:1px solid gray;padding:2px;margin:0;z-index:99999;overflow:hidden;cursor:move;'+(typeof w.style.borderRadius === 'string' ? 'background-color:#eaeaea;padding-top:0px;border-radius:4px;box-shadow:0 0 15px rgba(0,0,0,.4);' : 'background:-o-skin("Window Skin");')); w.id = wId; w.closeWin = function() { doc.removeEventListener('keydown', keyDown, false); gBrowser.tabpanels.removeEventListener('mousedown', mouseDown, false); this.parentNode.removeChild(this); w = null; }; w.addEle = function(str, style) { var ele = doc.createElementNS(xhtmlns, 'div'); ele.setAttribute('style', style); if (str) { ele.innerHTML = str; for (var el, all = ele.getElementsByTagName('*'), i = all.length; i--;) { el = all[i]; if (/^(script|frame|iframe|applet|embed|object)$/i.test(el.nodeName)) { el.parentNode.removeChild(el); } else { for (var att = el.attributes, j = att.length; j--;) { if (/^on[a-z]+$/i.test(att[j].name))att[j].value = ''; } } } } return this.appendChild(ele); }; var img = doc.createElementNS(xhtmlns, 'div'); img.setAttribute('style', 'display:block;float:right;width:16px;height:16px;padding:0;margin-top:2px;margin-right:1px;border:none;cursor:pointer;background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACQUlEQVR4Xm2SPUhbURTHfzfNJ4nU0Axx7CJCN2kQtIgVCtq6OdQuBUftWIQqFNsKDo6iHTqIqN3a0kklUKTS2AZrcOjioFtRjFWUfH+803cS9GHwB4dzcu75/+8L9xgaSEDbLXhaASzAyXAMn5/DHxwwjeJgKLRxd3Q0atxuLhGgWqmQmp9PJ7LZJ5Ow3WhQFweDG20LC1FfRwc3kUsm+T48fPIzl3s8VTdxxLt+/2FhdlZkc1MkmdR8Pba2ajlrz3z1+9OvIOaIfb7DwsSEyNKSyM6OSLksEo/rbw2ttadntV7Gnv3k86VfqskvmDzv7hZ580Zkelrk4kJqFIsii4satVrRs+rYmBQHBuRvS4u8g/fuCmDOz+HgAIWpKRgfh3AYhoZQ8Hqxjo4o9PdT3d1FcQEl8KoBnJ7C/j6KZkZGYG4OIhEUFed7erD29q69jGrd1qVBqcQVKgwEuMSEQhjtXRk4JvW/kM1i2WGMga4uzMoKBIOIfbNiolEC6+uU+/qQRALFA1QBlwVYxmBcLmhuxqytQSgEKu7t1dBavwKvbeINh/Has2IMqnXpem4bky6qWLdvZgaOj2FwEHNyoqG19vRMZ8jZs1+NOfsNcZS3EFvzeNL51laRe/dEYrFadsLpZeyZDx7P6QN4Btwx1OE1xO4HAquP2tsjAZ+Pm8gWi3xMpc6W8/kXPyAO/DM4oOsZa2pafdjZGXF7PAgOpXKZL4nE2XImcyUGMDSg63kbhgvgtYCq8+akIL4J3y7Fyn+DokZOnLlMyQAAAABJRU5ErkJggg==");background:-o-skin("Caption Close Button Skin");'); img.title = (win.navigator.language.indexOf('ru') == 0) ? '\u0417\u0430\u043A\u0440\u044B\u0442\u044C' : 'Close'; img.addEventListener('click', function() {this.parentNode.closeWin();}, false); w.appendChild(img); var title = w.addEle(title, 'display:table;color:#000;font:17px Times New Roman;width:auto;height:auto;padding:0;margin:0 2px;cursor:text;'); title.onclick = e => { e.preventDefault(); var url = e.target.href; // Здесь открываем url как хотим. var ctabpos = gBrowser.selectedTab._tPos +1; gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addWebTab(url), ctabpos); doc.getElementById(wId).closeWin(); }; var cnt = doc.createElement("textarea"); cnt.style.cssText = ` color: #000; width: 310px; height: 160px; outline: none; padding-left: 3px; padding-bottom: 3px; border: 1px solid #aaa; background-color: #fafcfe; font: 17px Times New Roman; `; if (text) cnt.value = text; w.append(cnt); w.addEle(status, 'display:table;font:12px Times New Roman;font-weight:bold;color:blue;width:auto;height:auto;padding-top:2px;margin:0 3px;cursor:pointer;'); w.addEventListener('mousedown', function(e) { if (e.target == w) { e.preventDefault(); var grabX = e.clientX, grabY = e.clientY, origX = parseInt(w.style.left), origY = parseInt(w.style.top); var mouseMove = function(ev) { w.style.left = origX+ev.clientX-grabX+'px'; w.style.top = origY+ev.clientY-grabY+'px'; }; doc.addEventListener('mousemove', mouseMove, false); doc.addEventListener('mouseup', function() {doc.removeEventListener('mousemove', mouseMove, false);}, false); } }, false); doc.documentElement.appendChild(w); if (size) { cnt.style.height = size.height; cnt.style.width = size.width; } else { for (var i = 3; i < 10; i++) { if (cnt.scrollHeight > cnt.offsetHeight || cnt.scrollWidth > cnt.offsetWidth) { cnt.style.height = 80*i+'px'; cnt.style.width = 160*i+'px'; } else break; } } var docEle = (doc.compatMode == 'CSS1Compat' && win.postMessage) ? doc.documentElement : doc.body; var mX = docEle.clientWidth-w.offsetWidth, mY = docEle.clientHeight-w.offsetHeight; if (mX < 0) {cnt.style.width = parseInt(cnt.style.width)+mX+'px'; mX = 0;} if (mY < 0) {cnt.style.height = parseInt(cnt.style.height)+mY+'px'; mY =0;} var hW = parseInt(w.offsetWidth/2); w.style.left = (pos && pos.X < mX+hW ? (pos.X > hW ? pos.X-hW : 0) : mX)+'px'; w.style.top = (pos && pos.Y+10 < mY ? pos.Y+10 : mY)+'px'; w.style.visibility = 'visible'; doc.addEventListener('keydown', keyDown, false); gBrowser.tabpanels.addEventListener('mousedown', mouseDown, false); if (text) { var st = cnt.style; var div = cnt.editor.rootElement; var range = new Range(); range.selectNode(div.firstChild); var rect = range.getBoundingClientRect(); let w = Math.ceil(rect.width); if (cnt.scrollTopMax) { if (!matchMedia("(-moz-overlay-scrollbars)").matches) // ??? w += InspectorUtils.getChildrenForNode(div, true, false).at(-1).clientWidth; } else st.height = Math.max(50, Math.ceil(rect.height) + 2) + "px"; st.width = Math.max(200, w) + "px"; } return w; }; var getHash = function (txt) { TKK=eval('((function(){var a\x3d817046147;var b\x3d-335196159;return 410049+\x27.\x27+(a+b)})())'); function sM(a) { var b; if (null !== yr) b = yr; else { b = wr(String.fromCharCode(84)); var c = wr(String.fromCharCode(75)); b = [b(), b()]; b[1] = c(); b = (yr = window[b.join(c())] || "") || ""; } var d = wr(String.fromCharCode(116)), c = wr(String.fromCharCode(107)), d = [d(), d()]; d[1] = c(); c = "&" + d.join("") + "="; d = b.split("."); b = Number(d[0]) || 0; for (var e = [], f = 0, g = 0; g < a.length; g++) { var l = a.charCodeAt(g); 128 > l ? e[f++] = l : (2048 > l ? e[f++] = l >> 6 | 192 : (55296 == (l & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (l = 65536 + ((l & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = l >> 18 | 240, e[f++] = l >> 12 & 63 | 128) : e[f++] = l >> 12 | 224, e[f++] = l >> 6 & 63 | 128), e[f++] = l & 63 | 128); } a = b; for (f = 0; f < e.length; f++) a += e[f], a = xr(a, "+-a^+6"); a = xr(a, "+-3^+b+-f"); a ^= Number(d[1]) || 0; 0 > a && (a = (a & 2147483647) + 2147483648); a %= 1E6; return c + (a.toString() + "." + (a ^ b)); } var yr = null; var wr = function(a) { return function() { return a; }; }, xr = function(a, b) { for (var c = 0; c < b.length - 2; c += 3) { var d = b.charAt(c + 2), d = "a" <= d ? d.charCodeAt(0) - 87 : Number(d), d = "+" == b.charAt(c + 1) ? a >>> d : a << d; a = "+" == b.charAt(c) ? a + d & 4294967295 : a ^ d; } return a; }; return sM(txt); }; var ujs_google_translate = function (dir) { var lng = window.navigator.language.slice(0, 2), txt = gContextMenu.selectionInfo.fullText, l = dir.split('|'); var encTxt = encodeURIComponent(txt); var winWait = function(lng) {createWindow('', (lng == 'ru' ? 'Подождите идет перевод' : 'Wait, is going Translating')+'\u2026', 'Google Translate', '_gt', window.navigator.lastClick);}; if (txt) { winWait(lng); var xhr = new XMLHttpRequest(); var url = 'https://translate.google.com/translate_a/single?client=gtx&sl=' + l[0] + '&tl=' + l[1] + '&hl=' + lng + '&eotf=0&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t' + getHash(txt); var urlt = "http://translate.google.com/translate_t?text="+encTxt+"&sl=' + langFrom_google_text + '&tl=' + langTo_google_text +'&hl=' + lng + '&eotf=0&ujs=gtt"; xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xhr.onreadystatechange = function() { try { if (xhr.readyState == 4 && xhr.status == 200) { var result = '', status = '', tmp = JSON.parse(xhr.responseText.replace(/\[(?=,)/g, '[0').replace(/,(?=,|\])/g, ',0').replace(/\\n/g, ' ')); for (var i = 0, n; n = tmp[0][i]; i++) { if (n[0])result += n[0].toString(); }; status = tmp[8][0][0].toUpperCase() + ' -\u203A ' + l[1].toUpperCase(); createWindow(result, status, '<a href="'+urlt.replace(/&/g,'&')+'" target="_blank" style="display:inline;padding:0;margin:0;text-decoration:none;border:none;color:#009;font:16px Times New Roman;">Google Translate</a>', '_gt', window.navigator.lastClick); } } catch(e) {}; }; xhr.send('q=' + encodeURIComponent(txt)); } else { var urlt = gBrowser.currentURI.spec; var url = "http://translate.google.com/translate?u="+encodeURIComponent(urlt)+'&tl='+l[1]+"&hl="+lng+"&langpair="+dir+"&tbb=1"; var ctabpos = gBrowser.selectedTab._tPos +1; gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addWebTab(url), ctabpos); }; }; var contextMenu = document.getElementById("contentAreaContextMenu"); var nextEleMenu = document.getElementById("context-inspect"); var menuItem = document.createXULElement("menuitem"); menuItem.setAttribute("id", "context-ru-google-translate"); menuItem.setAttribute("label", "Перевести на русский"); menuItem.setAttribute("class", "menuitem-iconic"); menuItem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='17' height='16'><path fill='rgb(0, 116, 232)' fill-opacity='context-fill-opacity' d='M15.37 15H17l-3.63-8.54a.75.75 0 0 0-.69-.46h-.82c-.3 0-.58.18-.7.46L9.32 10.8l-.01-.01a10.8 10.8 0 0 1-3.27-2.2 12.38 12.38 0 0 0 2.54-4.18L9.08 3H10V1.5H5.75V0h-1.5v1.5H0V3h7.5l-.33.91c-.47 1.31-1.2 2.52-2.13 3.56-.7-.9-1.25-1.9-1.63-2.97H1.8l.18.48a12.43 12.43 0 0 0 1.97 3.56c-.9.75-1.89 1.35-2.96 1.78v1.58a12.3 12.3 0 0 0 3.96-2.26 12.31 12.31 0 0 0 3.77 2.54L7.53 15h1.64l1.06-2.5h4.08l1.06 2.5Zm-4.5-4 1.4-3.3 1.4 3.3h-2.8Z'/></svg>"); menuItem.addEventListener("command", function() {ujs_google_translate('auto|ru');}, false); contextMenu.insertBefore(menuItem, nextEleMenu); contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu); var translate = async () => { var br = gBrowser.selectedBrowser; var fw = Services.focus.focusedWindow; if (fw == window) { if (document.activeElement != br) return; } else if (fw.browsingContext.top != br.browsingContext) return; var cb = navigator.clipboard; var was = await cb.readText(); if (was) await cb.writeText(""); docShell.doCommand("cmd_copy"); await new Promise(r => setTimeout(r, 100)); var txt = await cb.readText(); if (txt || was) cb.writeText(was); if (!txt && !br.currentURI.scheme.startsWith("http")) return; window.gContextMenu = {selectionInfo: { get fullText() { window.gContextMenu = null; return txt; } }}; ujs_google_translate("auto|ru"); } var ts = 0, destr = this.destructor, args = ["keyup", e => e.key == "Control" && ts - (ts = Cu.now()) > -300 && !e.shiftKey && !e.altKey && translate(ts = 0) ]; addEventListener(...args); this.destructor = () => destr(removeEventListener(...args)); } }).init(this);
Отсутствует
ucf_hookClicks.js – оптимизация скрипта меню и кнопок, устранены ошибки, больше не мусорит переменными в окно.
Меню быстрых опций запомнит ваши значения, а не только вшитые: щёлкаем строку "User Agent", вводим нужный вам ЮзерАгент в general.useragent.override_my. Работает для любых опций, например в строке "Загрузки" можно изменить пути сохранения страниц/графики. Дополнено меню пользователя, пока ещё в режиме окна, т.к. завязано на многие функции скрипта ucf_hookClicks.
SaveHTML.mjs - исправлены ошибки, в демо-профиле у background-скриптов теперь префикс «ucb_»
ucf_contextmenu_openwith.js от Vitaliy V. – убрал OpenClipboardURI, чтоб не путаться при кликах, добавил tooltips. Правый клик аналогичен левому с Shift и передаёт ссылку из буфера обмена или выделенного текста. Добавил roll - на строке "Ссылку в плеер MPV" клик колёсиком выполнит команду, указанную в подсказке. Для Linux могу сделать автопоиск терминала, но это усложнит код: path: '/usr/bin/sh', args: `-c "term=$(which konsole xterm xfce4-…`
Отсутствует
Было бы неплохо автору исправить это
Это в этом скрипте https://forum.mozilla-russia.org/viewto … 88#p781188
так понял, да вроде работало и с адресом, в любом случае проверить не могу версия 88 у меня не запускается как надо слишком старая
разбираться почему лень вероятно с wayland не дружит.
egorsemenov06
// menuItem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='17' height='16'><path fill='rgb(0, 116, 232)' fill-opacity='context-fill-opacity' d='M15.37 15H17l-3.63-8.54a.75.75 0 0 0-.69-.46h-.82c-.3 0-.58.18-.7.46L9.32 10.8l-.01-.01a10.8 10.8 0 0 1-3.27-2.2 12.38 12.38 0 0 0 2.54-4.18L9.08 3H10V1.5H5.75V0h-1.5v1.5H0V3h7.5l-.33.91c-.47 1.31-1.2 2.52-2.13 3.56-.7-.9-1.25-1.9-1.63-2.97H1.8l.18.48a12.43 12.43 0 0 0 1.97 3.56c-.9.75-1.89 1.35-2.96 1.78v1.58a12.3 12.3 0 0 0 3.96-2.26 12.31 12.31 0 0 0 3.77 2.54L7.53 15h1.64l1.06-2.5h4.08l1.06 2.5Zm-4.5-4 1.4-3.3 1.4 3.3h-2.8Z'/></svg>"); var image = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16'><path fill='context-fill rgb(0, 116, 232)' fill-opacity='context-fill-opacity' d='M15.37 15H17l-3.63-8.54a.75.75 0 0 0-.69-.46h-.82c-.3 0-.58.18-.7.46L9.32 10.8l-.01-.01a10.8 10.8 0 0 1-3.27-2.2 12.38 12.38 0 0 0 2.54-4.18L9.08 3H10V1.5H5.75V0h-1.5v1.5H0V3h7.5l-.33.91c-.47 1.31-1.2 2.52-2.13 3.56-.7-.9-1.25-1.9-1.63-2.97H1.8l.18.48a12.43 12.43 0 0 0 1.97 3.56c-.9.75-1.89 1.35-2.96 1.78v1.58a12.3 12.3 0 0 0 3.96-2.26 12.31 12.31 0 0 0 3.77 2.54L7.53 15h1.64l1.06-2.5h4.08l1.06 2.5Zm-4.5-4 1.4-3.3 1.4 3.3h-2.8Z'/></svg>"; var substitution = `ucf-${menuItem.id.toLowerCase()}-img`; var PHandler = Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler); if (!PHandler.hasSubstitution(substitution)) PHandler.setSubstitution(substitution, Services.io.newURI(image)); menuItem.style.cssText = `list-style-image:url("resource://${substitution}");-moz-context-properties:fill,fill-opacity;fill:currentColor;`;
Dobrov
Это то что сразу заметил, переменную length убрал выше и теперь здесь у тебя всегда submenu = false; будет https://github.com/VicDobrov/UserChrome … ith.js#L94
Да и если ты не заметил мой скрипт был обновлен, чтобы пункты при выделении текста и полях ввода были скрыты если это не URL
Отсутствует
Это в этом скрипте https://forum.mozilla-russia.org/viewto … 88#p781188
Да, я этот скрипт имел в виду. Зачем вообще убрали из адресной строки dropmarker - не пойму, с ним было очень удобно просматривать выпадающий список. А чтобы недоделку с вставляемой ссылкой устранить, это нужно сам скрипт править?
Отсутствует
egorsemenov06
скрытый текстВыделить кодКод:
// menuItem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='17' height='16'><path fill='rgb(0, 116, 232)' fill-opacity='context-fill-opacity' d='M15.37 15H17l-3.63-8.54a.75.75 0 0 0-.69-.46h-.82c-.3 0-.58.18-.7.46L9.32 10.8l-.01-.01a10.8 10.8 0 0 1-3.27-2.2 12.38 12.38 0 0 0 2.54-4.18L9.08 3H10V1.5H5.75V0h-1.5v1.5H0V3h7.5l-.33.91c-.47 1.31-1.2 2.52-2.13 3.56-.7-.9-1.25-1.9-1.63-2.97H1.8l.18.48a12.43 12.43 0 0 0 1.97 3.56c-.9.75-1.89 1.35-2.96 1.78v1.58a12.3 12.3 0 0 0 3.96-2.26 12.31 12.31 0 0 0 3.77 2.54L7.53 15h1.64l1.06-2.5h4.08l1.06 2.5Zm-4.5-4 1.4-3.3 1.4 3.3h-2.8Z'/></svg>"); var image = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16'><path fill='context-fill rgb(0, 116, 232)' fill-opacity='context-fill-opacity' d='M15.37 15H17l-3.63-8.54a.75.75 0 0 0-.69-.46h-.82c-.3 0-.58.18-.7.46L9.32 10.8l-.01-.01a10.8 10.8 0 0 1-3.27-2.2 12.38 12.38 0 0 0 2.54-4.18L9.08 3H10V1.5H5.75V0h-1.5v1.5H0V3h7.5l-.33.91c-.47 1.31-1.2 2.52-2.13 3.56-.7-.9-1.25-1.9-1.63-2.97H1.8l.18.48a12.43 12.43 0 0 0 1.97 3.56c-.9.75-1.89 1.35-2.96 1.78v1.58a12.3 12.3 0 0 0 3.96-2.26 12.31 12.31 0 0 0 3.77 2.54L7.53 15h1.64l1.06-2.5h4.08l1.06 2.5Zm-4.5-4 1.4-3.3 1.4 3.3h-2.8Z'/></svg>"; var substitution = `ucf-${menuItem.id.toLowerCase()}-img`; var PHandler = Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler); if (!PHandler.hasSubstitution(substitution)) PHandler.setSubstitution(substitution, Services.io.newURI(image)); menuItem.style.cssText = `list-style-image:url("resource://${substitution}");-moz-context-properties:fill,fill-opacity;fill:currentColor;`;
СПАСИБО!!!!!Не глянете кнопку Save что то я поменял на svg-иконки и пропали все пункты Сохранить изобржения как и если можно зарегистрировать в resource:// иконки
//Save........................................ (async () => CustomizableUI.createWidget({ id: "ucf-cbbtn-Save", tooltiptext: "Сохранить", localized: false, get initCode() { delete this.initCode; return this.initCode = Cu.readUTF8URI(Services.io.newURI( "chrome://user_chrome_files/content/custom_scripts/custom_script/Save.js" )); }, cbu: { types: { 128: "Bool", boolean: "Bool", 64: "Int", number: "Int", 32: "String", string: "String" }, getPrefs(pref) { try { return Services.prefs[`get${ this.types[Services.prefs.getPrefType(pref)] }Pref`](pref); } catch {return null;} }, setPrefs(pref, val) { Services.prefs[`set${this.types[typeof val]}Pref`](pref, val); } }, gClipboard: { get ch() { delete this.ch; return this.ch = Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper); }, write(str) { this.ch.copyStringToClipboard(str, Services.clipboard.kGlobalClipboard); } }, custombuttonsUtils: { writeFile(path, data) { try { if (path.includes(":\\")) path = path.replace(/\//g, "\\"); var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); file.initWithPath(path); file.exists() && file.remove(false); var strm = Cc["@mozilla.org/network/file-output-stream;1"] .createInstance(Ci.nsIFileOutputStream); strm.init(file, 0x04 | 0x08, 420, 0); strm.write(data, data.length); strm.flush(); strm.close(); } catch(ex) { Cu.reportError("Custom Buttons: " + [path, "---", ex, ex.stack].join("\n")); } } }, addDestructor(destructor, context) { this._destructors.push({destructor, context}); }, addEventListener(...args) { var trg = args[3]; if (!trg) trg = args[3] = this.ownerGlobal; trg.addEventListener(...args); this._handlers.push(args); }, onCreated(btn) { var win = btn.ownerGlobal; btn._handlers = new win.Array(); btn._destructors = new win.Array(); win.addEventListener("unload", this, {once: true}); new win.Function( "self,_id,cbu,xhtmlns,addDestructor,addEventListener,gClipboard,custombuttonsUtils", this.initCode ).call( btn, btn, this.id, this.cbu, "http://www.w3.org/1999/xhtml", this.addDestructor.bind(btn), this.addEventListener.bind(btn), this.gClipboard, this.custombuttonsUtils ); btn.setAttribute("image", this.image); }, get image() { var img = `${this.id.toLowerCase()}-img`; Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler) .setSubstitution(img, Services.io.newURI("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M3 .6C1.6.6.6 1.6.6 3v10c0 1.4 1 2.4 2.4 2.4h10c1.4 0 2.4-1 2.4-2.4V4.84L11.2.602Zm5.4 5.8h2V1m-2 0v5.4H7L5.6 5V1m-2 14v-2.6l1-1h6.8l1 1V15'/></svg>")); delete this.image; return this.image = `resource://${img}`; }, handleEvent(e) { var btn = e.target.getElementById(this.id); for(var args of btn._handlers) args.pop().removeEventListener(...args); delete btn._handlers; for(var {destructor, context} of btn._destructors) try {destructor.call(context, "destructor");} catch(ex) {Cu.reportError(ex);} delete btn._destructors; } }))();
self.label = "Save"; self._handleClick =()=> menuPopup.openPopup(this, "after_start"); var folderpath="C:\\Users\\Роман\\Desktop"; var array = [ { label: "Сохранить значок веб-сайта", func: "saveFavicon()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='context-fill' fill-opacity='context-fill-opacity'><path d='M8.5 1a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15zm2.447 1.75a6.255 6.255 0 0 1 3.756 5.125h-2.229A9.426 9.426 0 0 0 10.54 2.75h.407zm-2.049 0a8.211 8.211 0 0 1 2.321 5.125H5.781A8.211 8.211 0 0 1 8.102 2.75h.796zm-2.846 0h.408a9.434 9.434 0 0 0-1.934 5.125H2.297A6.254 6.254 0 0 1 6.052 2.75zm0 11.5a6.252 6.252 0 0 1-3.755-5.125h2.229A9.426 9.426 0 0 0 6.46 14.25h-.408zm2.05 0a8.211 8.211 0 0 1-2.321-5.125h5.437a8.211 8.211 0 0 1-2.321 5.125h-.795zm2.846 0h-.409a9.418 9.418 0 0 0 1.934-5.125h2.229a6.253 6.253 0 0 1-3.754 5.125z'/></svg>"}, { label: "Запомнить значок веб-сайта как base64", func: "copyFaviconData()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0zM9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1zM6.646 7.646a.5.5 0 1 1 .708.708L5.707 10l1.647 1.646a.5.5 0 0 1-.708.708l-2-2a.5.5 0 0 1 0-.708l2-2zm2.708 0 2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L10.293 10 8.646 8.354a.5.5 0 1 1 .708-.708z'/></svg>"}, { separator: ''}, { label: "Сохранить ярлык страницы как…", func: "saveShortcuts()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='context-fill' fill-opacity='context-fill-opacity'><path d='M8.5 1a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15zm2.447 1.75a6.255 6.255 0 0 1 3.756 5.125h-2.229A9.426 9.426 0 0 0 10.54 2.75h.407zm-2.049 0a8.211 8.211 0 0 1 2.321 5.125H5.781A8.211 8.211 0 0 1 8.102 2.75h.796zm-2.846 0h.408a9.434 9.434 0 0 0-1.934 5.125H2.297A6.254 6.254 0 0 1 6.052 2.75zm0 11.5a6.252 6.252 0 0 1-3.755-5.125h2.229A9.426 9.426 0 0 0 6.46 14.25h-.408zm2.05 0a8.211 8.211 0 0 1-2.321-5.125h5.437a8.211 8.211 0 0 1-2.321 5.125h-.795zm2.846 0h-.409a9.418 9.418 0 0 0 1.934-5.125h2.229a6.253 6.253 0 0 1-3.754 5.125z'/></svg>"}, { separator: ''}, { label: "Кодировать изображение(текст.файл) в base64", func: "copyFaviconbase()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.646 5.646a.5.5 0 1 1 .708.708L5.707 8l1.647 1.646a.5.5 0 0 1-.708.708l-2-2a.5.5 0 0 1 0-.708l2-2zm2.708 0 2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L10.293 8 8.646 6.354a.5.5 0 1 1 .708-.708z'/></svg>"}, { separator: ''}, { label: "Сохранить всю страницу как PDF", func: "savePageToPDF()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(142, 142, 152);fill-opacity:context-fill-opacity'><path d='M5.523 12.424c.14-.082.293-.162.459-.238a7.878 7.878 0 0 1-.45.606c-.28.337-.498.516-.635.572a.266.266 0 0 1-.035.012.282.282 0 0 1-.026-.044c-.056-.11-.054-.216.04-.36.106-.165.319-.354.647-.548zm2.455-1.647c-.119.025-.237.05-.356.078a21.148 21.148 0 0 0 .5-1.05 12.045 12.045 0 0 0 .51.858c-.217.032-.436.07-.654.114zm2.525.939a3.881 3.881 0 0 1-.435-.41c.228.005.434.022.612.054.317.057.466.147.518.209a.095.095 0 0 1 .026.064.436.436 0 0 1-.06.2.307.307 0 0 1-.094.124.107.107 0 0 1-.069.015c-.09-.003-.258-.066-.498-.256zM8.278 6.97c-.04.244-.108.524-.2.829a4.86 4.86 0 0 1-.089-.346c-.076-.353-.087-.63-.046-.822.038-.177.11-.248.196-.283a.517.517 0 0 1 .145-.04c.013.03.028.092.032.198.005.122-.007.277-.038.465z'/><path fill-rule='evenodd' d='M4 0h5.293A1 1 0 0 1 10 .293L13.707 4a1 1 0 0 1 .293.707V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2zm5.5 1.5v2a1 1 0 0 0 1 1h2l-3-3zM4.165 13.668c.09.18.23.343.438.419.207.075.412.04.58-.03.318-.13.635-.436.926-.786.333-.401.683-.927 1.021-1.51a11.651 11.651 0 0 1 1.997-.406c.3.383.61.713.91.95.28.22.603.403.934.417a.856.856 0 0 0 .51-.138c.155-.101.27-.247.354-.416.09-.181.145-.37.138-.563a.844.844 0 0 0-.2-.518c-.226-.27-.596-.4-.96-.465a5.76 5.76 0 0 0-1.335-.05 10.954 10.954 0 0 1-.98-1.686c.25-.66.437-1.284.52-1.794.036-.218.055-.426.048-.614a1.238 1.238 0 0 0-.127-.538.7.7 0 0 0-.477-.365c-.202-.043-.41 0-.601.077-.377.15-.576.47-.651.823-.073.34-.04.736.046 1.136.088.406.238.848.43 1.295a19.697 19.697 0 0 1-1.062 2.227 7.662 7.662 0 0 0-1.482.645c-.37.22-.699.48-.897.787-.21.326-.275.714-.08 1.103z'/></g></svg>"}, { label: "Сохранить всю страницу или выбранное как HTML", func: "savePageToHTML()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='16' height='16' viewBox='0 0 512 512'><g style='fill:context-fill rgb(142, 142, 152);fill-opacity:context-fill-opacity'><path d='M378.413 0H195.115L185.8 9.314 57.02 138.102l-9.314 9.314v278.69c0 47.36 38.528 85.895 85.896 85.895h244.811c47.353 0 85.881-38.535 85.881-85.895V85.896C464.294 38.528 425.766 0 378.413 0zm54.084 426.105c0 29.877-24.214 54.091-54.084 54.091H133.602c-29.884 0-54.098-24.214-54.098-54.091V160.591h83.716c24.885 0 45.077-20.178 45.077-45.07V31.804h170.116c29.87 0 54.084 24.214 54.084 54.092v340.209z' class='st0'/><path d='M163.164 253.19c-5.097 0-8.867 3.652-8.867 9.482v23.453c0 .489-.251.734-.726.734h-26.993c-.475 0-.726-.245-.726-.734v-23.453c0-5.831-3.771-9.482-8.868-9.482-5.222 0-8.993 3.652-8.993 9.482v65.144c0 5.83 3.645 9.475 8.868 9.475 5.111 0 8.993-3.645 8.993-9.475v-24.305c0-.489.251-.734.726-.734h26.993c.475 0 .726.244.726.734v24.305c0 5.83 3.77 9.475 8.867 9.475 5.223 0 8.993-3.645 8.993-9.475v-65.144c0-5.831-3.77-9.482-8.993-9.482zM235.249 253.923h-47.284c-5.46 0-8.993 3.282-8.993 8.023 0 4.615 3.533 7.897 8.993 7.897h13.978c.488 0 .726.244.726.726v57.247c0 5.711 3.771 9.475 8.882 9.475 5.223 0 8.993-3.764 8.993-9.475v-57.247c0-.482.237-.726.726-.726h13.978c5.46 0 8.993-3.282 8.993-7.897.001-4.742-3.532-8.023-8.992-8.023zM318.253 253.19c-5.348 0-8.267 2.919-10.934 9.238l-17.26 39.862h-.489l-17.623-39.862c-2.794-6.319-5.712-9.238-11.06-9.238-5.948 0-9.845 4.134-9.845 10.697v64.781c0 5.467 3.408 8.623 8.268 8.623 4.622 0 8.029-3.156 8.029-8.623V288.8h.6l12.89 29.653c2.541 5.837 4.608 7.541 8.742 7.541 4.133 0 6.2-1.704 8.756-7.541l12.764-29.653h.601v39.868c0 5.467 3.281 8.623 8.141 8.623 4.874 0 8.156-3.156 8.156-8.623v-64.781c-.002-6.564-3.773-10.697-9.736-10.697zM389.36 320.645h-29.408c-.489 0-.726-.244-.726-.734v-57.24c0-5.712-3.77-9.482-8.867-9.482-5.237 0-8.993 3.77-8.993 9.482v64.899c0 5.349 3.518 8.993 8.993 8.993h39.002c5.475 0 8.994-3.282 8.994-8.022-.001-4.615-3.52-7.896-8.995-7.896z' class='st0'/></g></svg>"}, { label: "Сохранить выделенный текст как txt файл", func: "saveSelectionToTxt()", image: "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0zM9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1zM4.5 9a.5.5 0 0 1 0-1h7a.5.5 0 0 1 0 1h-7zM4 10.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 1 0-1h4a.5.5 0 0 1 0 1h-4z'/></svg>"}, { separator: ''}, { label: "Запомнить изображение как base64, в контекстном меню", value: "Save.WebScreenShotOnImage"}, { label: "Сохранить выделенный текст в файл, в контекстном меню", value: "Save.SelectionToFile" }, { label: "Открыть выделенный текст в внешнем редакторе, в контекстном меню", value: "Save.TextToEditor"}, ]; var menuPopup = self.appendChild(document.createXULElement("menupopup")); array.forEach((m,i)=> { if ("separator" in m) { menuPopup.appendChild(document.createXULElement("menuseparator")); return }; var mItem = menuPopup.appendChild(document.createXULElement("menuitem")); mItem.setAttribute("label", m.label); mItem.setAttribute("class", "menuitem-iconic"); if ("image" in m) mItem.setAttribute("image", m.image || array[i-1].image); if ("value" in m) { mItem.setAttribute('type', 'checkbox'); mItem.setAttribute('checked', cbu.getPrefs(m.value) ); mItem.onclick =()=> cbu.setPrefs(m.value, !cbu.getPrefs(m.value)); } if ("func" in m) mItem.addEventListener("command", ()=> eval(m.func.toString())); }); menuPopup.setAttribute("onclick", "event.stopPropagation()"); function aDate() { var t=new Date(); var y=1900+t.getYear(); var min=t.getMinutes(); if (min<10){min="0"+min}; var h=t.getHours(); var m=t.getMonth();switch(m){case 0: m="января";break;case 1: m="февраля";break;case 2: m="марта";break;case 3: m="апреля";break;case 4: m="мая";break;case 5: m="июня";break;case 6: m="июля";break;case 7: m="августа";break;case 8: m="сентября";break;case 9: m="октября";break;case 10: m="ноября";break;default: m="декабря";} var d=t.getDate(); var curdate=d+" "+m+" "+y+" "+"г"; var myfilename=curdate; return myfilename; } function WebScreenShotonImage(image) { var canvas = document.createElementNS(xhtmlns, 'canvas'); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; var ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); var base64 = canvas.toDataURL(); gClipboard.write(base64); var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); var uri = makeURI('data:text/css,'+ encodeURIComponent('#alertImage { height: 25px !important; width: 25px !important; }')); sss.loadAndRegisterSheet(uri, 0); // alertsService.showAlertNotification(base64, self.label, "Запомнил изображение как base64", false, "", (s, t)=> { Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService).showAlertNotification(base64, self.label, "Изображение копировано как base64", false, "", (s, t)=> { if (t == 'alertfinished') sss.unregisterSheet(uri, 0); }, ""); }; var saveToFile = function (fileContent, fileName) { var uc = Components.classes['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Components.interfaces.nsIScriptableUnicodeConverter); uc.charset = 'utf-8'; fileContent = uc.ConvertFromUnicode(fileContent); var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes['@mozilla.org/filepicker;1'].createInstance(nsIFilePicker); fp.init(window.browsingContext, '', fp.modeSave); fp.defaultString = fileName; fp.appendFilters(fp.filterHTML); fp.appendFilters(fp.filterAll); fp.open(function (rv) { if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) { var stream = Components.classes['@mozilla.org/network/file-output-stream;1'].createInstance(Components.interfaces.nsIFileOutputStream); stream.init(fp.file, 0x02|0x20|0x08, 0666, 0); stream.write(fileContent, fileContent.length); stream.close(); } }); }; function savePageToHTML() { var vert = String.raw`javascript:(function(){var getSelWin=function(w){if(w.getSelection().toString())return w;for(var i=0,f,r;f=w.frames[i];i++){try{if(r=getSelWin(f))return r}catch(e){}}};var selWin=getSelWin(window),win=selWin||window,doc=win.document,loc=win.location;var qualifyURL=function(url,base){if(!url||/^([a-z]+:|%23)/.test(url))return url;var a=doc.createElement('a');if(base){a.href=base;a.href=a.protocol+(url.charAt(0)=='/'%3F(url.charAt(1)=='/'%3F'':'//'+a.host):'//'+a.host+a.pathname.slice(0,(url.charAt(0)!='%3F'&&a.pathname.lastIndexOf('/')+1)||a.pathname.length))+url}else{a.href=url};return a.href};var encodeImg=function(src,obj){var canvas,img,ret=src;if(/^https%3F:%5C/%5C//.test(src)){canvas=doc.createElement('canvas');if(!obj||obj.nodeName.toLowerCase()!='img'){img=doc.createElement('img');img.src=src}else{img=obj};if(img.complete)try{canvas.width=img.width;canvas.height=img.height;canvas.getContext('2d').drawImage(img,0,0);ret=canvas.toDataURL((/%5C.jpe%3Fg/i.test(src)%3F'image/jpeg':'image/png'))}catch(e){};if(img!=obj)img.src='about:blank'};return ret};var toSrc=function(obj){var strToSrc=function(str){var chr,ret='',i=0,meta={'%5Cb':'%5C%5Cb','%5Ct':'%5C%5Ct','%5Cn':'%5C%5Cn','%5Cf':'%5C%5Cf','%5Cr':'%5C%5Cr','%5Cx22':'%5C%5C%5Cx22','%5C%5C':'%5C%5C%5C%5C'};while(chr=str.charAt(i++)){ret+=meta[chr]||chr};return'%5Cx22'+ret+'%5Cx22'},arrToSrc=function(arr){var ret=[];for(var i=0;i<arr.length;i++){ret[i]=toSrc(arr[i])||'null'};return'['+ret.join(',')+']'},objToSrc=function(obj){var val,ret=[];for(var prop in obj){if(Object.prototype.hasOwnProperty.call(obj,prop)&&(val=toSrc(obj[prop])))ret.push(strToSrc(prop)+': '+val)};return'{'+ret.join(',')+'}'};switch(Object.prototype.toString.call(obj).slice(8,-1)){case'Array':return arrToSrc(obj);case'Boolean':case'Function':case'RegExp':return obj.toString();case'Date':return'new Date('+obj.getTime()+')';case'Math':return'Math';case'Number':return isFinite(obj)%3FString(obj):'null';case'Object':return objToSrc(obj);case'String':return strToSrc(obj);default:return obj%3F(obj.nodeType==1&&obj.id%3F'document.getElementById('+strToSrc(obj.id)+')':'{}'):'null'}};var ele,pEle,clone,reUrl=/(url%5C(%5Cx22%3F)(.+%3F)(%5Cx22%3F%5C))/g;if(selWin){var rng=win.getSelection().getRangeAt(0);pEle=rng.commonAncestorContainer;ele=rng.cloneContents()}else{pEle=doc.documentElement;ele=(doc.body||doc.getElementsByTagName('body')[0]).cloneNode(true)};while(pEle){if(pEle.nodeType==1){clone=pEle.cloneNode(false);clone.appendChild(ele);ele=clone};pEle=pEle.parentNode};var sel=doc.createElement('div');sel.appendChild(ele);for(var el,all=sel.getElementsByTagName('*'),i=all.length;i--;){el=all[i];if(el.style&&el.style.backgroundImage)el.style.backgroundImage=el.style.backgroundImage.replace(reUrl,function(a,b,c,d){return b+encodeImg(qualifyURL(c))+d});switch(el.nodeName.toLowerCase()){case'link':case'style':case'script':el.parentNode.removeChild(el);break;case'a':case'area':if(el.hasAttribute('href')&&el.getAttribute('href').charAt(0)!='%23')el.href=el.href;break;case'img':case'input':if(el.hasAttribute('src'))el.src=encodeImg(el.src,el);break;case'audio':case'video':case'embed':case'frame':case'iframe':if(el.hasAttribute('src'))el.src=el.src;break;case'object':if(el.hasAttribute('data'))el.data=el.data;break;case'form':if(el.hasAttribute('action'))el.action=el.action;break}};var head=ele.insertBefore(doc.createElement('head'),ele.firstChild);var meta=doc.createElement('meta');meta.httpEquiv='content-type';meta.content='text/html; charset=utf-8';head.appendChild(meta);var title=doc.getElementsByTagName('title')[0];if(title)head.appendChild(title.cloneNode(true));head.copyScript=function(){if('$'in win)return;var f=doc.createElement('iframe');f.src='about:blank';f.setAttribute('style','position:fixed;left:0;top:0;visibility:hidden;width:0;height:0;');doc.documentElement.appendChild(f);var str,script=doc.createElement('script');script.type='text/javascript';for(var name in win){if(name in f.contentWindow||!/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name))continue;try{str=toSrc(win[name]);if(!/%5C{%5Cs*%5C[native code%5C]%5Cs*%5C}/.test(str)){script.appendChild(doc.createTextNode('var '+name+' = '+str.replace(/<%5C/(script>)/ig,'<%5C%5C/$1')+';%5Cn'))}}catch(e){}};f.parentNode.removeChild(f);if(script.childNodes.length)this.nextSibling.appendChild(script)};head.copyScript();head.copyStyle=function(s){if(!s)return;var style=doc.createElement('style');style.type='text/css';if(s.media&&s.media.mediaText)style.media=s.media.mediaText;try{for(var i=0,rule;rule=s.cssRules[i];i++){if(rule.type!=3){if((!rule.selectorText||rule.selectorText.indexOf(':')!=-1)||(!sel.querySelector||sel.querySelector(rule.selectorText))){style.appendChild(doc.createTextNode(rule.cssText.replace(reUrl,function(a,b,c,d){var url=qualifyURL(c,s.href);if(rule.type==1&&rule.style&&rule.style.backgroundImage)url=encodeImg(url);return b+url+d})+'%5Cn'))}}else{this.copyStyle(rule.styleSheet)}}}catch(e){if(s.ownerNode)style=s.ownerNode.cloneNode(false)};this.appendChild(style)};var sheets=doc.styleSheets;for(var j=0;j<sheets.length;j++)head.copyStyle(sheets[j]);head.appendChild(doc.createTextNode('%5Cn'));var doctype='',dt=doc.doctype;if(dt&&dt.name){doctype+='<!DOCTYPE '+dt.name;if(dt.publicId)doctype+=' PUBLIC %5Cx22'+dt.publicId+'%5Cx22';if(dt.systemId)doctype+=' %5Cx22'+dt.systemId+'%5Cx22';doctype+='>%5Cn'};var href = 'data:text/html;charset=utf-8,' + encodeURIComponent(doctype + sel.innerHTML + '\n<!-- This document saved from ' + (loc.protocol != 'data:' ? loc.href : 'data:uri') + ' -->');var a = document.documentElement.appendChild(document.createElement("a"));a.setAttribute("href", href);var name = selWin ? win.getSelection().toString() : (title && title.text ? title.text : loc.pathname.split('/').pop());name=name.replace(/[:\\\/<>?*|"]+/g, '_').replace(/\s+/g, ' ').slice(0, 100).replace(/^\s+|\s+$/g, '');name += (function () {var d = new Date(), z=function(n){return '_' + (n < 10 ? '0' : '') + n};return z(d.getHours()) + z(d.getMinutes()) + z(d.getSeconds());})();a.setAttribute("download", name + ".html");a.click();a.remove();})();`; gBrowser.fixupAndLoadURIString(vert, {triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()}); }; function saveShortcuts() { var file = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsIFile); file.initWithPath(folderpath); if( !file.exists() || !file.isDirectory() ) { file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0x1B6);} var savetodir=folderpath+"\\"; var urllink=gBrowser.currentURI.spec; var out=getTabLabel(); var filename=savetodir+out+'.url'; var data="[InternetShortcut]\r\nURL="+urllink+"\r\n"; saveToFile(data, filename); var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); var uri = makeURI('data:text/css,'+ encodeURIComponent('#alertImage { height: 25px !important; width: 25px !important; }')); sss.loadAndRegisterSheet(uri, 0); var notific = 'Сохранил в: ' + folderpath; var image = gBrowser.selectedBrowser.mIconURL; Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService).showAlertNotification(image, filename, notific); }; function copyFaviconbase(){ var fp = window.makeFilePicker(); fp.init(window.browsingContext, "Открыть файл", fp.modeOpen); fp.appendFilter("Text and images", "*.txt; *.text; *.css; *.js; *.ini; *.rdf; *.xml; *.html; *.htm; *.shtml; *.xhtml; *.jpe; *.jpg; *.jpeg;\ *.gif; *.png; *.bmp; *.ico; *.svg; *.svgz; *.tif; *.tiff; *.ai; *.drw; *.pct; *.psp; *.xcf; *.psd; *.raw"); fp.open(re=> { if ( re != fp.returnOK ) return; var file = fp.file; var inputStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); inputStream.init(file, 0x01, 0600, 0); var stream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream); stream.setInputStream(inputStream); var encoded = btoa(stream.readBytes(stream.available())); var contentType = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService).getTypeFromFile(file); var dataURI = "data:" + contentType + ";charset=utf-8;base64," + encoded; gClipboard.write(dataURI); //Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService).showAlertNotification(dataURI, self.label, "Текст скопирован как base64"); var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); var uri = makeURI('data:text/css,'+ encodeURIComponent('#alertImage { height: 25px !important; width: 25px !important; }')); sss.loadAndRegisterSheet(uri, 0); // alertsService.showAlertNotification(base64, self.label, "Изображение скопировано как base64", false, "", (s, t)=> { Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService).showAlertNotification(dataURI, self.label, "Изображение скопировано как base64", false, "", (s, t)=> { if (t == 'alertfinished') sss.unregisterSheet(uri, 0); }, ""); }); }; function savePageToPDF() { var loc = gBrowser.currentURI.spec; var vert = "http://pdfmyurl.com?url=" + loc; gBrowser.fixupAndLoadURIString(vert, { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal() }); }; if (typeof window.saveImageURL != "function") var saveImageURL = internalSave.length == 16 ? (url, name, a3, a4, a5, a6, a7, type, a9, priv, prin) => internalSave(url, null, null, name, a9, type, a4, a3, null, a6, null, a7, a5, null, priv, prin) : internalSave.length == 15 ? (url, name, a3, a4, a5, a6, a7, type, a9, priv, prin) => internalSave(url, null, name, a9, type, a4, a3, null, a6, null, a7, a5, null, priv, prin) : (url, name, a3, a4, a5, a6, a7, type, a9, priv, prin) => internalSave(url, null, name, a9, type, a4, a3, null, a6, a7, a5, null, priv, prin); function saveFavicon() { var uri = gBrowser.currentURI; function getSiteName() { try { var domain = uri.host.split('.') } catch(e) { return "" }; domain = (domain.length == 2) ? domain[0] : domain[1] return domain.charAt(0).toUpperCase() + domain.slice(1).split('.')[0] + " "; }; var url = gBrowser.selectedTab.image; url && saveImageURL( url, getSiteName(), null, false, false, null, null, /^data:(image\/[^;,]+)/i.test(url) ? RegExp.$1.toLowerCase() : Cc["@mozilla.org/mime;1"] .getService(Ci.nsIMIMEService).getTypeFromURI(Services.io.newURI(url)), null, PrivateBrowsingUtils.isContentWindowPrivate(content || window), document.nodePrincipal ); }; function copyFaviconData() { var img = new Image(); img.src = gBrowser.selectedTab.image; WebScreenShotonImage(img); }; (popup => addEventListener("popupshowing", { handleEvent(e) { if (this.shouldHide) return; var menuitem = document.createXULElement("menuitem"); menuitem.id = "content-baseItem"; menuitem.className = "menuitem-iconic"; menuitem.setAttribute("oncommand", "copyImageAsBase64()"); menuitem.setAttribute("label", "Запомнить изображение как base64"); menuitem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0zM9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1zM6.646 7.646a.5.5 0 1 1 .708.708L5.707 10l1.647 1.646a.5.5 0 0 1-.708.708l-2-2a.5.5 0 0 1 0-.708l2-2zm2.708 0 2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L10.293 10 8.646 8.354a.5.5 0 1 1 .708-.708z'/></svg>"); popup.append(menuitem); addDestructor(() => menuitem.remove()); menuitem.copyImageAsBase64 = () => { var {osPid} = gContextMenu.actor.manager.browsingContext.currentWindowGlobal; if (osPid == -1) osPid = Services.appinfo.processID; for(var ind = 0, len = Services.ppmm.childCount; ind < len; ind++) { var pmm = Services.ppmm.getChildAt(ind); if (pmm.osPid == osPid) break; } pmm.loadProcessScript("data:;charset=utf-8," + encodeURIComponent(this.code()), false); } this.handleEvent = () => menuitem.hidden = this.shouldHide; }, get shouldHide() { return !(gContextMenu.onImage && Services.prefs.getBoolPref("Save.WebScreenShotOnImage", false)); }, code: () => `(targetIdentifier => { var image = ChromeUtils.import("resource://gre/modules/ContentDOMReference.jsm") .ContentDOMReference.resolve(targetIdentifier); var canvas = image.ownerDocument.createElementNS("${xhtmlns}", "canvas"); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; var ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0); var base64 = canvas.toDataURL(); Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper) .copyStringToClipboard(base64, Ci.nsIClipboard.kGlobalClipboard); Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService) .showAlertNotification(base64, "${self.label}", "Запомнил изображение как base64"); })(${ JSON.stringify(gContextMenu.targetIdentifier) })` }, false, popup || 1))(document.getElementById("contentAreaContextMenu")); function saveSelectionToTxt() { var {length} = saveURL, splice = length > 9, l11 = length == 11; var msgName = _id + ":Save:GetSelection"; var receiver = msg => { var args = [ "data:text/plain," + encodeURIComponent(gBrowser.currentURI.spec + "\r\n\r\n" + msg.data), getTabLabel() + ' ' + aDate().replace(/:/g, ".") + ".txt", null, false, false, null, window.document ]; splice && args.splice(5, 0, null) && l11 && args.splice(1, 0, null); saveURL(...args); } messageManager.addMessageListener(msgName, receiver); addDestructor(() => messageManager.removeMessageListener(msgName, receiver)); var func = fm => { var res, fed, win = {}; var fe = fm.getFocusedElementForWindow(content, true, win); var sel = (win = win.value).getSelection(); if (sel.isCollapsed) { var ed = fe && fe.editor; if (ed && ed instanceof Ci.nsIEditor) sel = ed.selection, fed = fe; } if (sel.isCollapsed) fed && fed.blur(), docShell.doCommand("cmd_selectAll"), res = win.getSelection().toString(), docShell.doCommand("cmd_selectNone"), fed && fed.focus(); res = res || sel.toString(); /\S/.test(res) && sendAsyncMessage("NAME", res); } var url = "data:charset=utf-8," + encodeURIComponent(`(${func})`.replace("NAME", msgName)) + '(Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager));'; (saveSelectionToTxt = () => gBrowser.selectedBrowser.messageManager.loadFrameScript(url, false))(); } ((contextMenu, el)=> { var saveItem = contextMenu.insertBefore(document.createXULElement("menuitem"), el); saveItem.id = "content-saveItem"; saveItem.setAttribute("label", "Сохр./добавить выбранный текст в файл"); saveItem.setAttribute("class", "menuitem-iconic"); saveItem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(142, 142, 152);fill-opacity:context-fill-opacity'><path d='M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zm-3 0A1.5 1.5 0 0 1 9.5 3V1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4.5h-2z'/><path d='M4 6.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-.5.5h-7a.5.5 0 0 1-.5-.5v-7zm0-3a.5.5 0 0 1 .5-.5H7a.5.5 0 0 1 0 1H4.5a.5.5 0 0 1-.5-.5z'/></g></svg>"); saveItem.onclick =()=> saveSelectionToFile(); var editorItem = contextMenu.insertBefore(document.createXULElement("menuitem"), el); editorItem.id = "content-editorItem"; editorItem.setAttribute("label", "Открыть выбранный текст в редакторе"); editorItem.setAttribute("class", "menuitem-iconic"); editorItem.setAttribute("image", "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0zM9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1zM4.5 9a.5.5 0 0 1 0-1h7a.5.5 0 0 1 0 1h-7zM4 10.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 1 0-1h4a.5.5 0 0 1 0 1h-4z'/></svg>"); editorItem.onclick =()=> textToEditor(); addEventListener('popupshowing', e=> { if (e.target != e.currentTarget) return; var sel = gContextMenu.isTextSelected; saveItem.hidden = !sel || !cbu.getPrefs("Save.SelectionToFile"); editorItem.hidden = !sel || !cbu.getPrefs("Save.TextToEditor"); }, false, contextMenu); addDestructor(()=> { saveItem.remove(); editorItem.remove(); }); })(document.getElementById("contentAreaContextMenu"), document.getElementById("context-sep-open")); function saveSelectionToFile() { var line = ".".repeat(62) + "\n"; var hint = "Нажмите чтобы открыть файл"; var prfx = "Выделенный текст сохранен в файл "; var img = self.getAttribute("image"); var desk = Services.dirsvc.get("Desk", Ci.nsIFile); var as = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService); (saveSelectionToFile = async () => { var time = aDate(), url = gBrowser.currentURI.displaySpec; var text = `${line}${getTabLabel()} - ${time}\n${url}\n\n${ gContextMenu.contentData.selectionInfo.fullText }\n\n\n`; try { var file = Services.prefs.getComplexValue("browser.download.dir", Ci.nsIFile); var msg = prfx + "в папку " + file.leafName; await IOUtils.makeDirectory(file.path); } catch(ex) { file && Cu.reportError(ex); file = desk.clone(); var msg = prfx + "на рабочий стол"; } file.append(`Save - ${time}.txt`); await IOUtils.writeUTF8(file.path, text, {mode: file.exists() ? "append" : "create"}); var name = "sstf-" + Cu.now(); as.showAlertNotification( gBrowser.selectedTab.image || img, msg, hint, true, "", (s, t) => t == "alertclickcallback" && file.launch(), name ); setTimeout(as.closeAlert, 8e3, name); })(); }; function textToEditor() { let browserMM = gBrowser.selectedBrowser.messageManager; browserMM.addMessageListener('getSelect', function listener(message) { var text = convertFromUnicode("UTF-8", message.data); try {var file = Services.prefs.getComplexValue("browser.download.dir", Ci.nsIFile);} catch {file = Services.dirsvc.get("Desk", Ci.nsIFile);} file.append("TextToEditor.txt"); custombuttonsUtils.writeFile(file.path, text); file.launch(); browserMM.removeMessageListener('getSelect', listener, true); }); browserMM.loadFrameScript('data:,sendAsyncMessage("getSelect", content.document.getSelection().toString())', false); }; function convertFromUnicode(charset, str) { var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Components.interfaces.nsIScriptableUnicodeConverter); converter.charset = charset; str = converter.ConvertFromUnicode(str); return str + converter.Finish(); }; function getTabLabel() { var label = gBrowser.selectedTab.label; var label = label.replace(/[:+.\\\/<>?*|"]+/g, " ").replace(/\s\s+/g, " "); return label.substring(0, 50); }; ((main, parts) => this.onmousedown = e => { if (e.button) return; this.onmousedown = null; var df = MozXULElement.parseXULToFragment(` <menugroup orient="vertical"> <menuseparator/> <menuitem class="menuitem-iconic" image="data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M.002 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-12a2 2 0 0 1-2-2V3zm1 9v1a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12zm5-6.5a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0z'/></svg>" label="Сохранить всю страницу как PNG" value="all"/> <menuitem class="menuitem-iconic" image="data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M.002 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-12a2 2 0 0 1-2-2V3zm1 9v1a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12zm5-6.5a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0z'/></svg>" label="Сохранить видимую часть страницы как PNG" value="page"/> <menuitem class="menuitem-iconic" image="data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><g style='fill:context-fill rgb(142, 142, 152);fill-opacity:context-fill-opacity'><path d='M4.502 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z'/><path d='M14.002 13a2 2 0 0 1-2 2h-10a2 2 0 0 1-2-2V5A2 2 0 0 1 2 3a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v8a2 2 0 0 1-1.998 2zM14 2H4a1 1 0 0 0-1 1h9.002a2 2 0 0 1 2 2v7A1 1 0 0 0 15 11V3a1 1 0 0 0-1-1zM2.002 4a1 1 0 0 0-1 1v8l2.646-2.354a.5.5 0 0 1 .63-.062l2.66 1.773 3.71-3.71a.5.5 0 0 1 .577-.094l1.777 1.947V5a1 1 0 0 0-1-1h-10z'/></g></svg>" label="Сохранить выбранный элемент страницы как PNG" value="click"/> <menuitem class="menuitem-iconic" image="data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M1.5 2A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13zm7 6h5a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-5a.5.5 0 0 1-.5-.5v-3a.5.5 0 0 1 .5-.5z'/></svg>" label="Сохранить выбранную область страницы как PNG" value="clipping"/> </menugroup> `); var menugroup = df.firstChild; menugroup.setAttribute("context", ""); menugroup.setAttribute("oncommand", "handleCommand(event);"); menugroup.handleCommand = e => { var name = _id + ":DataURLReady"; main = main.replace("%MESSAGE_NAME%", name); var urls = {}, configurable = true, enumerable = true; Object.entries(parts).forEach(([key, part]) => Object.defineProperty(urls, key, { configurable, enumerable, get() { var value = `data:;charset=utf-8,({${ encodeURIComponent(main + part) }%0A}).init("${key}")`; Object.defineProperty(urls, key, {configurable, enumerable, value}); return value; }})); var getTabLabel = () => { var label = gBrowser.selectedTab.label; var label = label.replace(/[:+.\\\/<>?*|"]+/g, " ").replace(/\s\s+/g, " "); return label.substring(0, 50); } var listener = msg => { var fp = makeFilePicker(); fp.init(window.browsingContext, "Сохранить как…", fp.modeSave); fp.appendFilter("", "*.png"); fp.defaultString = getTabLabel() + ".png"; fp.open(res => { if (res == fp.returnCancel || !fp.file) return; var wbp = makeWebBrowserPersist(), args = [ Services.io.newURI(msg.data), document.nodePrincipal, null, null, null, null, fp.file, null ]; var {length} = wbp.saveURI; length >= 9 && splice(args); length == 10 && args.splice(3, 0, null); wbp.saveURI(...args); setTimeout(async lp => { var d = await Downloads.createDownload({ source: "about:blank", target: fp.file }); (await lp).add(d); d.refresh(d.succeeded = true); }, 777, Downloads.getList(Downloads.ALL)); }); } var splice = arr => { var fox74 = parseInt(Services.appinfo.platformVersion) >= 74; var args = [fox74 ? 7 : 2, 0, fox74 ? Ci.nsIContentPolicy.TYPE_IMAGE : null]; (splice = arr => arr.splice(...args))(arr); } messageManager.addMessageListener(name, listener); addDestructor(() => messageManager.removeMessageListener(name, listener)); (menugroup.handleCommand = e => gBrowser.selectedBrowser.messageManager .loadFrameScript(urls[e.target.value], false) )(e); } menuPopup.querySelector('menuitem[label*="ярлык"]').after(df); })(` init(cmd) { cmd.startsWith("c") ? this[cmd].init(this[cmd].parent = this) : this[cmd](); }, capture(win, x, y, width, height) { var canvas = win.document.createElementNS("${xhtmlns}", "canvas"); canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); var tryDraw = ind => { try {ctx.drawWindow(win, x, y, canvas.width, canvas.height, "white")} catch(ex) {canvas.height = ind * canvas.width; tryDraw(--ind);} } tryDraw(17); sendAsyncMessage("%MESSAGE_NAME%", canvas.toDataURL("image/png")); }, `, { all: `all() { var win = content; this.capture(win, 0, 0, win.innerWidth + win.scrollMaxX, win.innerHeight + win.scrollMaxY); }`, page: `page() { var win = content, doc = win.document, body = doc.body, html = doc.documentElement; var scrX = (body.scrollLeft || html.scrollLeft) - html.clientLeft; var scrY = (body.scrollTop || html.scrollTop) - html.clientTop; this.capture(win, scrX, scrY, win.innerWidth, win.innerHeight); }`, clipping: `clipping: { handleEvent(e) { if (e.button) return false; e.preventDefault(); e.stopPropagation(); switch(e.type) { case "mousedown": this.downX = e.pageX; this.downY = e.pageY; this.bs.left = this.downX + "px"; this.bs.top = this.downY + "px"; this.body.appendChild(this.box); this.flag = true; break; case "mousemove": if (!this.flag) return; this.moveX = e.pageX; this.moveY = e.pageY; if (this.downX > this.moveX) this.bs.left = this.moveX + "px"; if (this.downY > this.moveY) this.bs.top = this.moveY + "px"; this.bs.width = Math.abs(this.moveX - this.downX) + "px"; this.bs.height = Math.abs(this.moveY - this.downY) + "px"; break; case "mouseup": this.uninit(); break; } }, init() { var win = {}; Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager) .getFocusedElementForWindow(content, true, win); this.win = win.value; this.doc = this.win.document; this.body = this.doc.body; if (!HTMLBodyElement.isInstance(this.body)) { Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService) .showAlertNotification("${self.image}", ${JSON.stringify(self.label)}, "Не удается захватить!"); return false; } this.flag = null; this.box = this.doc.createElement("div"); this.bs = this.box.style; this.bs.border = "#0f0 dashed 2px"; this.bs.position = "absolute"; this.bs.zIndex = "2147483647"; this.defaultCursor = this.win.getComputedStyle(this.body, "").cursor; this.body.style.cursor = "crosshair"; ["click", "mouseup", "mousemove", "mousedown"].forEach(type=> this.doc.addEventListener(type, this, true)); }, uninit() { var pos = [this.win, parseInt(this.bs.left), parseInt(this.bs.top), parseInt(this.bs.width), parseInt(this.bs.height)]; this.body.style.cursor = this.defaultCursor; this.body.removeChild(this.box); this.parent.capture.apply(this, pos); ["click", "mouseup", "mousemove", "mousedown"].forEach(type=> this.doc.removeEventListener(type, this, true)); } }`, click: `click: { getPosition() { var html = this.doc.documentElement; var body = this.doc.body; var rect = this.target.getBoundingClientRect(); return [ this.win, Math.round(rect.left) + (body.scrollLeft || html.scrollLeft) - html.clientLeft, Math.round(rect.top) + (body.scrollTop || html.scrollTop) - html.clientTop, parseInt(rect.width), parseInt(rect.height) ]; }, highlight() { this.orgStyle = this.target.hasAttribute("style") ? this.target.style.cssText : false; this.target.style.cssText += "outline: red 2px solid; outline-offset: 2px; -moz-outline-radius: 2px;"; }, lowlight() { if (this.orgStyle) this.target.style.cssText = this.orgStyle; else this.target.removeAttribute("style"); }, handleEvent(e) { switch(e.type){ case "click": if (e.button) return; e.preventDefault(); e.stopPropagation(); this.lowlight(); this.parent.capture.apply(this, this.getPosition()); this.uninit(); break; case "mouseover": if (this.target) this.lowlight(); this.target = e.target; this.highlight(); break; } }, init() { this.win = content; this.doc = content.document; ["click", "mouseover"].forEach(type=> this.doc.addEventListener(type, this, true)); }, uninit() { this.target = false; ["click", "mouseover"].forEach(type=> this.doc.removeEventListener(type, this, true)); } }` });
Отсутствует
А чтобы недоделку с вставляемой ссылкой устранить, это нужно сам скрипт править?
У меня не воспроизводится dropmarker скрывается с настройкой hidewhenusertyping: true, пробовал на 88, вот только иконка dropmarker'а не загрузилась заменил arrow-down.svg на arrow-dropdown-16.svg. А так да для новых версий нужно править.
Отредактировано Vitaliy V. (12-05-2024 16:45:06)
Отсутствует
Это то что сразу заметил, переменную length убрал выше и теперь здесь у тебя всегда submenu = false
Шеф, я усё исправил! – там arrOS.length надо было, т.к. имена текущей OS и массивов равны.
Поправил мой мод ucf_contextmenu_openwith.js в соответствии с новой версией, упростил и дополнил.
Скрыл OpenClipboardURI, чтоб было однозначное поведение при кликах, добавил подсказки. Правый клик аналогичен левому с Shift и передаёт ссылку из буфера обмена или выделенного текста. Добавил roll - выполнение другой команды. В строке "yt-dlp" клик колёсиком подставит другие опции.
Vitaliy V. - шапку обновил, добавив ссылку на твой скрипт ucf_contextmenuopenwith.js.
Мне сложно проверять, обновился пост или нет, гитхабом или чем-то подобным это проще и удобней отслеживать!
Отредактировано Dobrov (12-05-2024 03:54:01)
Отсутствует
egorsemenov06
вставитьскрытый текстВыделить кодКод:
var PHandler = Services.io.getProtocolHandler("resource") .QueryInterface(Ci.nsIResProtocolHandler), count = 0;
перед
array.forEach((m,i)=> {и заменить тут
скрытый текстВыделить кодКод:
// if ("image" in m) mItem.setAttribute("image", m.image || array[i-1].image); if ("image" in m) { let substitution = `ucf-cbbtn-save-${++count}-img`; if (!PHandler.hasSubstitution(substitution)) PHandler.setSubstitution(substitution, Services.io.newURI(m.image || array[i-1].image)); mItem.style.cssText = `list-style-image:url("resource://${substitution}");-moz-context-properties:fill,fill-opacity;fill:currentColor;`; }
Спасибо Большое!!!! Но в кнопке так и не появились пункты от "Сохранить всю страницу как PNG" до "Сохранить выбранную область страницы как PNG" и еще там для контекстного меню три иконки зарегистрировать бы в resource://. Помогите пожалуйста! В консоли пишет вот такую ошибку Uncaught Error: not well-formed XML
parseXULToFragment chrome://global/content/customElements.js:554
onmousedown chrome://user_chrome_files/content/custom_scripts/custom_script.js line 126 > Function:383
customElements.js:554:17
Отредактировано egorsemenov06 (12-05-2024 09:02:06)
Отсутствует
В консоли пишет вот такую ошибку Uncaught Error: not well-formed XML
Странно, у меня ничего подобного не пишет, XML'ка подхватывается.
Заресурсить SVG'шки попробовал так:
Код Save.js — оставил без изменений, таким, как ты выложил.
А в коде создания виджета — убрал get image() {…},
и заменил get initCode() {…}, на такой
// get initCode() { var count = 0; var prfx = "ucf-cbbtn-save-resurl-"; var rph = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler); var ss = url => { var subst = prfx + ++count; rph.setSubstitution(subst, Services.io.newURI(url)); return "resource://" + subst; } this.image = ss("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M3 .6C1.6.6.6 1.6.6 3v10c0 1.4 1 2.4 2.4 2.4h10c1.4 0 2.4-1 2.4-2.4V4.84L11.2.602Zm5.4 5.8h2V1m-2 0v5.4H7L5.6 5V1m-2 14v-2.6l1-1h6.8l1 1V15'/></svg>"); var arr = [ "@-moz-document url(chrome://browser/content/browser.xhtml) {", ` #${this.id} menuitem, #content-baseItem, #content-saveItem, #content-editorItem {`, " fill: currentColor !important;", " -moz-context-properties: fill, fill-opacity !important;", " }", " @media (-moz-platform: windows) {", ` #${this.id} menugroup > menuitem {`, " padding-block: .5em !important;", " padding-inline-start: 1em !important;", " }", " }", "}" ]; var url = "data:text/css;charset=utf-8," + encodeURIComponent(arr.join("\n")); var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); sss.loadAndRegisterSheet(Services.io.newURI(ss(url)), sss.USER_SHEET); delete this.initCode; return this.initCode = Cu.readUTF8URI(Services.io.newURI( "chrome://user_chrome_files/content/custom_scripts/custom_script/Save.js" )) .replace(/data:image\/svg[^"]+/g, ss); },
Отсутствует
egorsemenov06 пишетВ консоли пишет вот такую ошибку Uncaught Error: not well-formed XML
Странно, у меня ничего подобного не пишет, XML'ка подхватывается.
Заресурсить SVG'шки попробовал так:
Код Save.js — оставил без изменений, таким, как ты выложил.
А в коде создания виджета — убрал get image() {…},
и заменил get initCode() {…}, на такойскрытый текстВыделить кодКод:
// get initCode() { var count = 0; var prfx = "ucf-cbbtn-save-resurl-"; var rph = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler); var ss = url => { var subst = prfx + ++count; rph.setSubstitution(subst, Services.io.newURI(url)); return "resource://" + subst; } this.image = ss("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path style='fill:none;stroke:context-fill rgb(142, 142, 152);stroke-opacity:context-fill-opacity;stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round;' d='M3 .6C1.6.6.6 1.6.6 3v10c0 1.4 1 2.4 2.4 2.4h10c1.4 0 2.4-1 2.4-2.4V4.84L11.2.602Zm5.4 5.8h2V1m-2 0v5.4H7L5.6 5V1m-2 14v-2.6l1-1h6.8l1 1V15'/></svg>"); var arr = [ "@-moz-document url(chrome://browser/content/browser.xhtml) {", ` #${this.id} menuitem, #content-baseItem, #content-saveItem, #content-editorItem {`, " fill: currentColor !important;", " -moz-context-properties: fill, fill-opacity !important;", " }", " @media (-moz-platform: windows) {", ` #${this.id} menugroup > menuitem {`, " padding-block: .5em !important;", " padding-inline-start: 1em !important;", " }", " }", "}" ]; var url = "data:text/css;charset=utf-8," + encodeURIComponent(arr.join("\n")); var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService); sss.loadAndRegisterSheet(Services.io.newURI(ss(url)), sss.USER_SHEET); delete this.initCode; return this.initCode = Cu.readUTF8URI(Services.io.newURI( "chrome://user_chrome_files/content/custom_scripts/custom_script/Save.js" )) .replace(/data:image\/svg[^"]+/g, ss); },
Для пунктов в <menugroup> (это, наверно, те, которые у тебя потерялись),
там прописан padding, а то что-то у меня его почти совсем никакого не видно.
Можно указать свои значения, или удалить строки @media блока, если не требуется.
СПАСИБО БОЛЬШОЕ!!!!!!Теперь лакшери!
Отсутствует
Но в кнопке так и не появились пункты от "Сохранить всю страницу как PNG"
О даже не посмотрел что там иконки ещё есть думал они в начале только
Отсутствует