Полезная информация

Пользователи не любят читать документацию. Станьте оригинальным, будьте не как все. Ознакомьтесь с нашей базой знаний.

№827620-04-2020 15:25:11

Paukan
Участник
 
Группа: Members
Зарегистрирован: 18-04-2020
Сообщений: 10
UA: Firefox 68.0

Re: Настройка внешнего вида Firefox в userChrome.css

sandro79, завел чистый профиль, работает!

PS. Подскажите кто-нибудь, как скрыть текст "поиск" в таком html?

Выделить код

Код:

<form id="quick-search" method="post" action="">
	<input type="hidden" name="max" value="1">
	<input type="hidden" name="to" value="1">
	поиск
        <input id="search-text" type="text" name="nm" accesskey="ы" value="" class="hint" style="width: 150px;">

Отсутствует

 

№827720-04-2020 16:44:17

RadeD
Участник
 
Группа: Members
Зарегистрирован: 20-04-2020
Сообщений: 3
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Подскажите пожалуйста. Взял у Ариса код скругления мегабара:

Выделить код

Код:

#urlbar[focused="true"]:not([usertyping="true"]) #urlbar-background,
#urlbar:not([open]) #urlbar-background,
#urlbar,#urlbar-input-container,
#searchbar, .searchbar-textbox
{
  border-radius: 7px !important;
}

Он работает, да
UT5Uf57.png
Но как только в МБ начинаешь что либо писать, он становиться вновь квадратным. Куда копать для того что бы скругление оставалось?
1Ds1i7w.png

Отсутствует

 

№827820-04-2020 17:06:44

kokoss
Участник
 
Группа: Members
Зарегистрирован: 15-02-2018
Сообщений: 1119
UA: Firefox 52.0

Re: Настройка внешнего вида Firefox в userChrome.css

RadeD
В about:config -> переключите параметр -> browser.urlbar.update1 на false и для скругления углов адресной строки используйте этот код: https://github.com/Aris-t2/CustomCSSforFx/blob/master/classic/css/locationbar/locationbar_border_roundness.css


Add, или так: https://forum.mozilla-russia.org/viewto … 74#p775574

Отредактировано kokoss (20-04-2020 17:17:01)


Win7

Отсутствует

 

№827920-04-2020 17:31:36

RadeD
Участник
 
Группа: Members
Зарегистрирован: 20-04-2020
Сообщений: 3
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

kokoss
Как отключить его то я знаю, но это не решит проблемы в корне. В 77-й версии локейшенбар будет отключен полностью, так что приспосабливаться придется в любом случае, отключай - не отключай МБ.

Add

Вот за это спасибо, вроде бы курил тему, но упустил это сообщение. Манипуляция с #urlbar.megabar как раз то, что нужно. Вопрос закрыт.

Отсутствует

 

№828020-04-2020 20:53:04

volaxus
Участник
 
Группа: Members
Зарегистрирован: 03-02-2020
Сообщений: 5
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

volaxus пишет
harryk пишет

volaxusДобавьте user.jsВыделить кодКод:// Запрет рамки, обводящей активную ссылку
user_pref("browser.display.focus_ring_on_anything", false); //ПУ
// Толщина рамки, обводящей активную ссылку
// 0 - невидимая
// 1 - тонкий пунктир. ПУ
// 2, 3, 4 - толще
user_pref("browser.display.focus_ring_width", 0);

Не помогает. Прикрепил скрин для наглядности

^up^

Отсутствует

 

№828120-04-2020 21:06:21

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

volaxus
Это стили сайта влияют а не браузера
в userContent.css

скрытый текст

@-moz-document domain("rutracker.org") {
.postLink .postImg {
    outline: none !important;
}
}

Отредактировано Vitaliy V. (20-04-2020 21:09:54)

Отсутствует

 

№828220-04-2020 21:17:36

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. можно ли адаптировать кнопку ночной режим
для user_chrome_files
иконка

скрытый текст
data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA014A7dNeAO0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNeAO3TXgDtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTXgDt014A7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA014A7dNeAO0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNeAO3TXgDtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTXgDt014A7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA014A7dNeAO0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNeAO3TXgDtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTXgDt014A7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA014A7dNeAO0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNeAO3TXgDtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTXgDt014A7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA014A7dNeAO0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDt014A7dNeAO3TXgDtAACsQX/+rEF//qxBf/6sQX/+rEF//qxBf/6sQX/+rEF//qxBf/6sQX/+rEF//qxBf/6sQX/+rEF//qxBAACsQQ==

инициализация

скрытый текст
(sss => {
    var pref = `CB.${_id.slice(20)}.setStyleForPage`;
    var url = "data:text/css," + encodeURIComponent(this.Help);
    var args = [Services.io.newURI(url), sss.AGENT_SHEET];
    var reg = add => {
        var has = sss.sheetRegistered(...args);
        if (add) has || sss.loadAndRegisterSheet(...args);
        else has && sss.unregisterSheet(...args);
    }
    var setState = () => {
        var state = Services.prefs.getBoolPref(pref, false);
        this.icon.style.backgroundColor = state ? "#696969" : "#CDBA96";
        reg(state);
    }
    setState();
    this._handleClick = () => Services.prefs.setBoolPref(
        pref, !Services.prefs.getBoolPref(pref, false)
    );
    Services.prefs.addObserver(pref, setState, false);
    addDestructor(reason => {
        Services.prefs.removeObserver(pref, setState);
        reason[5] == "e" && reg();
    });
})(
    Cc["@mozilla.org/content/style-sheet-service;1"]
        .getService(Ci.nsIStyleSheetService)
);

// Подсказка для кнопки ..........
this.tooltipText = self.label + "\nЛ: Переключить черный фон страниц";

Справка

скрытый текст
@-moz-document url-prefix(http://), url-prefix(https://), url-prefix(ftp://), url-prefix(file://), url(about:blank), url-prefix("about:neterror"){

/* Firefox Scrollbars */
scrollbar {opacity: .75 !important;}

/* Base */
*, ::before, ::after {
  color: #CCC !important;
  border-color: #444 !important;
  outline-color: #444 !important;
  text-shadow: none !important;
  box-shadow: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
}

html * {
  color: #CCC !important;
}

p::first-letter,
h1::first-letter,
h2::first-letter,
p::first-line {
  color: inherit !important;
  background: none !important;
}

/* :: Give solid BG :: */
/* element */
html,body,
li ul, ul li,
table, header,
article, section,
nav, menu,
aside,

/* common */
[class*="nav"],
[class*="open"],
[id*="ropdown"], /*dropdown*/
[class*="ropdown"],
div[class*="menu"],
[class*="tooltip"],
div[class*="popup"],
div[id*="popup"],

/* Notes, details, etc.  Maybe useful */
div[class*="note"], span[class*="note"],
div[id*="detail"],div[class*="detail"],
div[class*="description"],

/* Also common */
div[class*="content"], div[class*="container"],

/* Popup divs that use visibility: hidden and display: none */
div[style*="display: block"],
div[style*="visibility: visible"] {
  background-color: #404040 !important;
}

/*: No BG :*/
*:not(:empty):not(span):not([class="html5-volume-slider html5-draggable"]):not([class="html5-player-chrome html5-stop-propagation"]), *::before, *::after,
td:empty, p:empty, div:empty:not([role]):not([style*="flashblock"]):not([class^="html5"]):not([class*="noscriptPlaceholder"]) {
  background-image: none !important;
}

/*: Filter non-icons :*/
span:not(:empty):not([class*="icon"]):not([id*="icon"]):not([class*="star"]):not([id*="star"]):not([id*="rating"]):not([class*="rating"]):not([class*="prite"]) {
  background-image: none !important;
  text-indent: 0 !important;
}

/*: Image opacity :*/
img:not([id="mpiv-preview"]), svg { opacity: .75 !important; }
img:hover, svg:hover { opacity: 1 !important; }

/* Highlight */
::-moz-selection {
  background-color: #626F61 !important;
  color: #F6F7B9 !important;
}

/* ::: anchor/links ::: */
a {
  color: #71BAA5 !important;
  background-color: #696969 !important;
  opacity: 1 !important;
  text-indent: 0 !important;
}

a:link { color: #ACC7F6 !important; } /* hyperlink */
a:visited { color: #CDB4E7 !important; }
a:hover { color: #FFE900 !important; background-color: #363037 !important; }
a:active { color: #FFAE00 !important; }

/* "Top level" div */
body > div { background-color: inherit !important; }

/* :::::: Text Presentation :::::: */
summary, details { background-color: inherit !important; }
kbd, time, label, .date { color: #B6D2AC !important; }
acronym, abbr { border-bottom: 1px dotted !important; cursor: help !important; }
mark,code,pre,samp,blockquote { background-color: #282826 !important }

/* :::::: Headings :::::: */
h1,h2,h3,h4,h5,h6  {
  background-image: none !important;
  border-radius: 5px !important;
  text-indent: 0 !important;
}

h1,h2 { background-color: #28313E !important; }
h3,h4 { background-color: #2A3731 !important; }
h5,h6 { background-color: #372A2A !important; }

/* :::::: Tables, cells :::::: */
table table { background: #212121 !important; }
th, caption { background: #404040 !important; }

/* ::: Inputs, textareas ::: */
input, textarea, button,
select, option, optgroup {
  color: #DDD !important;
  background: none #404046 !important;
  -moz-appearance: none !important;
}

input,
textarea,
button {
  border-color: #000 !important;
  border-width: 1px !important;
}

/* :::::: Button styling :::::: */
input[type="button"],
input[type="submit"],
input[type="reset"],
button {
  background: #343855 !important;
}

input[type="button"]:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
button:hover {
  color: #FFF !important;
  background: #435B6B !important;
}

input[type="image"] { opacity: .85 !important; }
input[type="image"]:hover { opacity: .95 !important; }

/* Lightbox fix */
html [id*="lightbox"] * { background-color: transparent !important; }
html [id*="lightbox"] img { opacity: 1 !important; }

/* Youtube Annotation */
#movie_player-html5 .annotation { background: #333 !important; }

/* Mozilla addons shrink/expand sections */
.expando a { background: none transparent !important; }
}

@-moz-document url(about:newtab) {
window {
  background: #696969 !important;
}

#newtab-scrollbox {
  background: transparent none !important;
}

.newtab-title {
  background-color: rgba(0,0,0,.75) !important;
  color: #eee !important;
}
}

@-moz-document url(chrome://browser/content/browser.xul) {
/* Browser Background */
browser[type="content-primary"] {
  background-color: #1a1a1a !important;
}
}

и реализовать активацию таба мышенавидением

скрытый текст

//Активация таба мышенаведением
((lst, trg) => trg && addEventListener("mouseover", lst, false, trg))({
    id: 0,
    tab: null,
    handleEvent(e) {
        var tab = e.target.closest("tab:not([selected]");
        if (tab && this.tab != tab)
            clearTimeout(this.id),
            this.id = setTimeout(this.onTimeout, 850, this.tab = tab, tab.screenX);
    },
    get onTimeout() {
        delete this.onTimeout;
        return this.onTimeout = (tab, x) => {
            if (tab.matches(":hover") && Math.abs(x - tab.screenX) < 50)
                gBrowser.selectedTab = tab;
            this.tab = null;
        }
    }
}, gBrowser.tabs[0].flattenedTreeParentNode);

Отредактировано egorsemenov06 (20-04-2020 21:35:52)

Отсутствует

 

№828320-04-2020 21:28:29

oleg.sgh
Участник
 
Группа: Members
Зарегистрирован: 19-04-2014
Сообщений: 2987
UA: Firefox 68.0

Re: Настройка внешнего вида Firefox в userChrome.css

Программа Thunderbird.
Есть возможность намертво установить единые: шрифт, его размер и междустрочный интервал в самом письме?
Всё, что нарыл на форуме, касается или интерфейса, или работает криво в разных ящиках.

Отсутствует

 

№828420-04-2020 21:40:51

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

volaxus пишет

можно ли адаптировать кнопку ночной режим

в принципе можно, вот только со стилем не охота возится, вряд ли тот что в help корректно работает?

и реализовать активацию таба мышенавидением

я расширение использую tabs_focus
https://github.com/VitaliyVstyle/Vitali … xperiments
там ещё предпросмотр есть и перезагрузка по клику на вкладке

Отредактировано Vitaliy V. (20-04-2020 21:41:43)

Отсутствует

 

№828520-04-2020 21:58:09

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет
volaxus пишет

можно ли адаптировать кнопку ночной режим

в принципе можно, вот только со стилем не охота возится, вряд ли тот что в help корректно работает?

Работает по маленьку правда не на всех сайтах
за расширение большое спасибо

а этот код гугл переводчика возможно сделать для user_chrome_files

Выделить код

Код:

/*Initialization Code*/

var lc = navigator.lastClick = {};
addEventListener("mouseup", e => {
    if (e.button) return;
    lc.X = e.screenX - mozInnerScreenX;
    lc.Y = e.screenY - mozInnerScreenY;
}, false, gBrowser.tabpanels || 1);

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()};

   // закрыть окно переводчика кликом мимо окна
   gBrowser.addEventListener("click", function c() {
      this.removeEventListener("click", c );
      try { doc.getElementById(wId).closeWin() } catch(e) {};
   }, true );
    
    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);
        this.parentNode.removeChild(this);
    };
    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);
    };
     w.addEle1 = function(str, style){
        var ele = doc.createElementNS(xhtmlns, 'textarea');
        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 = w.addEle1(text, 'display:block;border:1px solid #aaa;padding-bottom:3px;padding-left:3px;background-color:#fafcfe;color:#000;font:16px Times New Roman;width:310px;height:160px;overflow:auto;cursor:text;-moz-user-focus:normal;-moz-user-select:text;');
    cnt.contentEditable="true";
    cnt.context="contentAreaContextMenu";
    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);
    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=t&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, "<br />"));
                    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,'&amp;')+'" 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 (x){LOG(x)};
        };
         xhr.send('q=' + encodeURIComponent(txt));
    } else {
        var urlt = gBrowser.currentURI.spec;  
        var url = "http://translate.google.com/translate?u="+encodeURIComponent(urlt)+"&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 menuId = "context-ext-google-translate";
var menuItem = document.getElementById(menuId);
if (menuItem) {
    contextMenu.removeChild(menuItem.nextElementSibling);
    contextMenu.removeChild(menuItem.nextElementSibling);
    contextMenu.removeChild(menuItem);
};

menuItem = document.createXULElement("menuitem");
menuItem.setAttribute("id", menuId);
menuItem.setAttribute("label", "Перевести на русский");
menuItem.setAttribute("class", "menuitem-iconic");
menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABBUlEQVR4Ac2RMU4DMRREB2MqihQpAkUaqnAduuQw4Sx03CGcJYIiDYqQ0lCsZ77535ZFcgAkRuPvV7zd/dLiz3N1PFb8hmRckrfELZrF9ONQ1B6Yz0MyM7S0O6zGkVprh/3+Kw/JzkHSpRpJKZkpr9fYbOx0cjVsCbWG31oHBM9mtt0q73ZcrdLhAMlYQKkUI22aqsNo8HKZAMQhvVaKSHWj2Q2aPU3mJQFY7nuHyvYFduP83WF3AJRfcPNYnr/Lp1G1uK4m9sno1LaUbnX/htf8BNzoneUD5NhjvLCMhURQSQ93QCZwXYjFwg3I0NZKrvoknQPMIHkt/jRAQKMeG2yX89/mB4EJbKbZxIhFAAAAAElFTkSuQmCC");
menuItem.addEventListener("command", function(){ujs_google_translate('auto|ru')}, false);
contextMenu.insertBefore(menuItem, nextEleMenu);

menuItem = document.createXULElement("menuitem");
menuItem.setAttribute("label", "Перевести на английский");
menuItem.setAttribute("class", "menuitem-iconic");
menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAAB5UlEQVR4AWOgPZg0c9+Oq2+qpx9LaQaiw4mNB27efbs2uXFNQh2Q4Zm9zSNth23MhqjGnXMC86vnHmUS4udxv7OvOd2yPE7PTlfCTk9GVVEoyJA7WI8dyPA0k3U1l+jJMV7CeThpTZeoKDdDUsvBPSff/V+6/P/Bvf///2+bdvU/EKRm/k9IBNIlfZe+LFrzvbsbyJ636pKkyQyQhoUb7tZNvPpw3/0/TfX/ISAm5n94BIiRm/n/xYsLd946ei4vajoiqDuRAejQf//+o4PQ0P9+fmhiQGVnrr1kXJNYG2zEzXDxDsPv3wy/fkFJoOTPn39+/fr/69e/37//AUX+/mXRkO458wWHDba2f8wswCyQ3N+/f//8/fP7z5+TV18w2Mdt6plzPiptx5Wr7/+/ffMzOR6kysjkt74hWMPfp06O+2dulZCeFZKwnkE4m8E8bN3i9aCQ+dxY96GrK6bkGJD9R1v3l6Y20NVW9kt+/v//ZdbcFwkxTVPPMQimM8XEqkb7a/zoqLxkH9v4zVyI5+///wyMmtKMmhJAnbLqQjHxaw5r2orOmZN5uj470Zahat6BKS7JzpmLBHXm8GhM5lCdcP7ai1ZpixZxk9NXXjKIFzOIFjAI54oY1vXuue5qmscw+AAAW0tKxtPoicEAAAAASUVORK5CYII=");
menuItem.addEventListener("command", function(){ujs_google_translate('auto|en')}, false);
contextMenu.insertBefore(menuItem, nextEleMenu);

contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu);

Отредактировано egorsemenov06 (20-04-2020 22:39:15)

Отсутствует

 

№828620-04-2020 22:06:10

volaxus
Участник
 
Группа: Members
Зарегистрирован: 03-02-2020
Сообщений: 5
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

volaxusЭто стили сайта влияют а не браузерав userContent.cssскрытый текст@-moz-document domain("rutracker.org") {.postLink .postImg {    outline: none !important;}}
                    Отредактировано Vitaliy V. (Сегодня 21:09:54)

Спасибо, помогло!

Отсутствует

 

№828721-04-2020 13:47:02

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06 пишет

а этот код гугл переводчика возможно сделать для user_chrome_files

скрытый текст

Выделить код

Код:

(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);
                    };
                    w.addEle1 = function(str, style) {
                        var ele = doc.createElementNS(xhtmlns, 'textarea');
                        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 = w.addEle1(text, 'display:block;border:1px solid #aaa;padding-bottom:3px;padding-left:3px;background-color:#fafcfe;color:#000;font:16px Times New Roman;width:310px;height:160px;overflow:auto;cursor:text;-moz-user-focus:normal;-moz-user-select:text;');
                    cnt.contentEditable="true";
                    cnt.context="contentAreaContextMenu";
                    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);
                    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, "<br />"));
                                    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,'&amp;')+'" 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)+"&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/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABBUlEQVR4Ac2RMU4DMRREB2MqihQpAkUaqnAduuQw4Sx03CGcJYIiDYqQ0lCsZ77535ZFcgAkRuPvV7zd/dLiz3N1PFb8hmRckrfELZrF9ONQ1B6Yz0MyM7S0O6zGkVprh/3+Kw/JzkHSpRpJKZkpr9fYbOx0cjVsCbWG31oHBM9mtt0q73ZcrdLhAMlYQKkUI22aqsNo8HKZAMQhvVaKSHWj2Q2aPU3mJQFY7nuHyvYFduP83WF3AJRfcPNYnr/Lp1G1uK4m9sno1LaUbnX/htf8BNzoneUD5NhjvLCMhURQSQ93QCZwXYjFwg3I0NZKrvoknQPMIHkt/jRAQKMeG2yX89/mB4EJbKbZxIhFAAAAAElFTkSuQmCC");
                menuItem.addEventListener("command", function() {ujs_google_translate('auto|ru');}, false);
                contextMenu.insertBefore(menuItem, nextEleMenu);

                menuItem = document.createXULElement("menuitem");
                menuItem.setAttribute("id", "context-en-google-translate");
                menuItem.setAttribute("label", "Перевести на английский");
                menuItem.setAttribute("class", "menuitem-iconic");
                menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAAB5UlEQVR4AWOgPZg0c9+Oq2+qpx9LaQaiw4mNB27efbs2uXFNQh2Q4Zm9zSNth23MhqjGnXMC86vnHmUS4udxv7OvOd2yPE7PTlfCTk9GVVEoyJA7WI8dyPA0k3U1l+jJMV7CeThpTZeoKDdDUsvBPSff/V+6/P/Bvf///2+bdvU/EKRm/k9IBNIlfZe+LFrzvbsbyJ636pKkyQyQhoUb7tZNvPpw3/0/TfX/ISAm5n94BIiRm/n/xYsLd946ei4vajoiqDuRAejQf//+o4PQ0P9+fmhiQGVnrr1kXJNYG2zEzXDxDsPv3wy/fkFJoOTPn39+/fr/69e/37//AUX+/mXRkO458wWHDba2f8wswCyQ3N+/f//8/fP7z5+TV18w2Mdt6plzPiptx5Wr7/+/ffMzOR6kysjkt74hWMPfp06O+2dulZCeFZKwnkE4m8E8bN3i9aCQ+dxY96GrK6bkGJD9R1v3l6Y20NVW9kt+/v//ZdbcFwkxTVPPMQimM8XEqkb7a/zoqLxkH9v4zVyI5+///wyMmtKMmhJAnbLqQjHxaw5r2orOmZN5uj470Zahat6BKS7JzpmLBHXm8GhM5lCdcP7ai1ZpixZxk9NXXjKIFzOIFjAI54oY1vXuue5qmscw+AAAW0tKxtPoicEAAAAASUVORK5CYII=");
                menuItem.addEventListener("command", function() {ujs_google_translate('auto|en');}, false);
                contextMenu.insertBefore(menuItem, nextEleMenu);

                contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu);
            }
        }).init(this);

Отредактировано Vitaliy V. (03-06-2021 12:09:37)

Отсутствует

 

№828821-04-2020 15:14:08

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет
egorsemenov06 пишет

а этот код гугл переводчика возможно сделать для user_chrome_files

Да в custom_script_win.js
ucf_custom_script_win

вообще ни чего не ясно ucf_custom_script_win это куда надо вставить?

ucf_custom_script_win.load а это куда? я вообще тупой нельзя ли пожалуйста для особо одареных по подробнее объяснить ?

Отредактировано egorsemenov06 (21-04-2020 15:20:28)

Отсутствует

 

№828921-04-2020 15:24:39

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06
ну вот как например там есть specialwidgets: { .... },
и this.specialwidgets.constructor();

также и это добавить туда
и перезапуск по ПКМ не забудьте...

Отредактировано Vitaliy V. (21-04-2020 15:27:51)

Отсутствует

 

№829021-04-2020 16:05:50

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06
ну вот как например там есть specialwidgets: { .... },
и this.specialwidgets.constructor();

также и это добавить туда
и перезапуск по ПКМ не забудьте...

Что я делаю не так

скрытый текст

Выделить код

Код:

// Этот скрипт работает в главном окне браузера если включено в настройках

var ucf_custom_script_win = {
    initialized: false,
    unloadlisteners: [],
    load: function() {
        if (this.initialized)
            return;
        this.initialized = true;
        // this.specialwidgets.constructor(); // <-- Special Widgets
        this.autohidesidebar.constructor(); // <-- Auto Hide Sidebar
	this.googletranslate.constructor();
        /* ************************************************ */

        // Здесь может быть ваш код который сработает по событию "load" не раньше

        /* ************************************************ */
        if (this.unloadlisteners.length < 1)
            return;
        window.addEventListener("unload", this, false);
    },
    handleEvent: function(event) {
        this[event.type](event);
    },
    unload: function() {
        window.removeEventListener("unload", this, false);
        this.unloadlisteners.forEach((str) => {
            try {
                this[str].destructor();
            } catch (e) {}
        });
    },
    specialwidgets: {
        _separator: null,
        _spacer: null,
        _spring: null,
        _timer: null,
        get Customizable() {
            delete this.Customizable;
            if ("createSpecialWidget" in window.CustomizableUI)
                return this.Customizable = window.CustomizableUI;
            var scope = null;
            try {
                scope = Components.utils.import("resource:///modules/CustomizableUI.jsm", {}).CustomizableUIInternal;
            } catch (e) { }
            return this.Customizable = scope;
        },
        constructor: function() {
            if (!("CustomizableUI" in window) || !("gCustomizeMode" in window))
                return;
            ucf_custom_script_win.unloadlisteners.push("specialwidgets");
            window.addEventListener("customizationready", this, false);
        },
        destructor: function() {
            window.removeEventListener("customizationready", this, false);
        },
        handleEvent: function(event) {
            if (event.type == "customizationchange") {
                clearTimeout(this._timer);
                this._timer = setTimeout(() => {
                    this.createSpecialWidgets();
                }, 1000);
            } else if (event.type == "customizationready") {
                if (this.Customizable !== null) {
                    this.createSpecialWidgets();
                    window.addEventListener("customizationchange", this, false);
                    window.addEventListener("customizationending", this, false);
                }
            } else if (event.type == "customizationending") {
                window.removeEventListener("customizationchange", this, false);
                window.removeEventListener("customizationending", this, false);
            }
        },
        createSpecialWidgets: function(event) {
            try {
                var fragment = document.createDocumentFragment();
                if (!this._spring || this.findSpecialWidgets(this._spring, "spring")) {
                    var spring = this.Customizable.createSpecialWidget("spring", document);
                    if (this._spring != null || (!this._spring && this.findSpecialWidgets(spring.id, "spring"))) {
                        spring.setAttribute("label", "Растягивающийся интервал");
                        fragment.appendChild(gCustomizeMode.wrapToolbarItem(spring, "palette"));
                    }
                    this._spring = spring.id;
                }
                if (!this._spacer || this.findSpecialWidgets(this._spacer, "spacer")) {
                    var spacer = this.Customizable.createSpecialWidget("spacer", document);
                    if (this._spacer != null || (!this._spacer && this.findSpecialWidgets(spacer.id, "spacer"))) {
                        spacer.setAttribute("label", "Интервал");
                        fragment.appendChild(gCustomizeMode.wrapToolbarItem(spacer, "palette"));
                    }
                    this._spacer = spacer.id;
                }
                if (!this._separator || this.findSpecialWidgets(this._separator, "separator")) {
                    var separator = this.Customizable.createSpecialWidget("separator", document);
                    if (this._separator != null || (!this._separator && this.findSpecialWidgets(separator.id, "separator"))) {
                        separator.setAttribute("label", "Разделитель");
                        fragment.appendChild(gCustomizeMode.wrapToolbarItem(separator, "palette"));
                    }
                    this._separator = separator.id;
                }
                gCustomizeMode.visiblePalette.appendChild(fragment);
            } catch (e) {}
        },
        findSpecialWidgets: function(eltid, string) {
            if (!eltid)
                return false;
            try {
                if (!gCustomizeMode.visiblePalette.querySelector("toolbar" + string + "[id^='" + eltid.split(string)[0] + string + "']"))
                    return true;
            } catch (e) {}
            return false;
        }
    },
    autohidesidebar: {
        sidebar: null,
        constructor: function() {
            var sidebar = this.sidebar = document.querySelector("#sidebar-box");
            if(!sidebar)
                return;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.addEventListener(type, this, false);
            });
            ucf_custom_script_win.unloadlisteners.push("autohidesidebar");
        },
        destructor: function() {
            var sidebar = this.sidebar;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.removeEventListener(type, this, false);
            });
        },
        handleEvent: function(event) {
            this[event.type](event);
        },
        dragenter: function() {
            if (!this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.setAttribute("sidebardrag", "true");
        },
        drop: function() {
            if (this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.removeAttribute("sidebardrag");
        },
        dragexit: function(event) {
            var sidebar = this.sidebar;
            var boxObj = sidebar.getBoundingClientRect(), boxScrn = !sidebar.boxObject ? sidebar : sidebar.boxObject;
            if ((!event.relatedTarget || event.screenY <= (boxScrn.screenY + 5) || event.screenY  >= (boxScrn.screenY + boxObj.height - 5)
                || event.screenX <= (boxScrn.screenX + 5) || event.screenX >= (boxScrn.screenX + boxObj.width - 5))
                && sidebar.hasAttribute("sidebardrag"))
                sidebar.removeAttribute("sidebardrag");
        }
    }
};
googletranslate: {
        constructor: function() {
            var lc = navigator.lastClick = {}, w = null, xhtmlns = 'http://www.w3.org/1999/xhtml';
            var mouseUp = function(e) {
                if (e.button) return;
                lc.X = e.screenX - mozInnerScreenX;
                lc.Y = e.screenY - mozInnerScreenY;
            };
            gBrowser.tabpanels.addEventListener('mouseup', mouseUp, false);
            this.destructor = function() {
                gBrowser.tabpanels.removeEventListener('mouseup', mouseUp, false);
                if (w)
                    w.closeWin();
            };
            ucf_custom_script_win.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);
                };
                w.addEle1 = function(str, style) {
                    var ele = doc.createElementNS(xhtmlns, 'textarea');
                    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 = w.addEle1(text, 'display:block;border:1px solid #aaa;padding-bottom:3px;padding-left:3px;background-color:#fafcfe;color:#000;font:16px Times New Roman;width:310px;height:160px;overflow:auto;cursor:text;-moz-user-focus:normal;-moz-user-select:text;');
                cnt.contentEditable="true";
                cnt.context="contentAreaContextMenu";
                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);
                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, "<br />"));
                                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,'&amp;')+'" 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)+"&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/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABBUlEQVR4Ac2RMU4DMRREB2MqihQpAkUaqnAduuQw4Sx03CGcJYIiDYqQ0lCsZ77535ZFcgAkRuPvV7zd/dLiz3N1PFb8hmRckrfELZrF9ONQ1B6Yz0MyM7S0O6zGkVprh/3+Kw/JzkHSpRpJKZkpr9fYbOx0cjVsCbWG31oHBM9mtt0q73ZcrdLhAMlYQKkUI22aqsNo8HKZAMQhvVaKSHWj2Q2aPU3mJQFY7nuHyvYFduP83WF3AJRfcPNYnr/Lp1G1uK4m9sno1LaUbnX/htf8BNzoneUD5NhjvLCMhURQSQ93QCZwXYjFwg3I0NZKrvoknQPMIHkt/jRAQKMeG2yX89/mB4EJbKbZxIhFAAAAAElFTkSuQmCC");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|ru');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            menuItem = document.createXULElement("menuitem");
            menuItem.setAttribute("id", "context-en-google-translate");
            menuItem.setAttribute("label", "Перевести на английский");
            menuItem.setAttribute("class", "menuitem-iconic");
            menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAAB5UlEQVR4AWOgPZg0c9+Oq2+qpx9LaQaiw4mNB27efbs2uXFNQh2Q4Zm9zSNth23MhqjGnXMC86vnHmUS4udxv7OvOd2yPE7PTlfCTk9GVVEoyJA7WI8dyPA0k3U1l+jJMV7CeThpTZeoKDdDUsvBPSff/V+6/P/Bvf///2+bdvU/EKRm/k9IBNIlfZe+LFrzvbsbyJ636pKkyQyQhoUb7tZNvPpw3/0/TfX/ISAm5n94BIiRm/n/xYsLd946ei4vajoiqDuRAejQf//+o4PQ0P9+fmhiQGVnrr1kXJNYG2zEzXDxDsPv3wy/fkFJoOTPn39+/fr/69e/37//AUX+/mXRkO458wWHDba2f8wswCyQ3N+/f//8/fP7z5+TV18w2Mdt6plzPiptx5Wr7/+/ffMzOR6kysjkt74hWMPfp06O+2dulZCeFZKwnkE4m8E8bN3i9aCQ+dxY96GrK6bkGJD9R1v3l6Y20NVW9kt+/v//ZdbcFwkxTVPPMQimM8XEqkb7a/zoqLxkH9v4zVyI5+///wyMmtKMmhJAnbLqQjHxaw5r2orOmZN5uj470Zahat6BKS7JzpmLBHXm8GhM5lCdcP7ai1ZpixZxk9NXXjKIFzOIFjAI54oY1vXuue5qmscw+AAAW0tKxtPoicEAAAAASUVORK5CYII=");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|en');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu);
        }
    },

if (window.document.readyState != "complete") {
    window.addEventListener("load", function load() {
        window.removeEventListener("load", load, false);
        ucf_custom_script_win.load();
    }, false);
} else
    ucf_custom_script_win.load();


перезапускал ПКМ

Отредактировано egorsemenov06 (21-04-2020 16:07:07)

Отсутствует

 

№829121-04-2020 16:13:12

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06
не туда добавлено, ладно вот полный custom_script_win.js

скрытый текст

Выделить код

Код:

// Этот скрипт работает в главном окне браузера если включено в настройках

var ucf_custom_script_win = {
    initialized: false,
    unloadlisteners: [],
    load: function() {
        if (this.initialized)
            return;
        this.initialized = true;
        // this.specialwidgets.constructor(); // <-- Special Widgets
        this.autohidesidebar.constructor(); // <-- Auto Hide Sidebar
        /* ************************************************ */
        this.googletranslate.constructor();
        // Здесь может быть ваш код который сработает по событию "load" не раньше

        /* ************************************************ */
        if (this.unloadlisteners.length < 1)
            return;
        window.addEventListener("unload", this, false);
    },
    handleEvent: function(event) {
        this[event.type](event);
    },
    unload: function() {
        window.removeEventListener("unload", this, false);
        this.unloadlisteners.forEach((str) => {
            try {
                this[str].destructor();
            } catch (e) {}
        });
    },
    googletranslate: {
        constructor: function() {
            var lc = navigator.lastClick = {}, w = null, xhtmlns = 'http://www.w3.org/1999/xhtml';
            var mouseUp = function(e) {
                if (e.button) return;
                lc.X = e.screenX - mozInnerScreenX;
                lc.Y = e.screenY - mozInnerScreenY;
            };
            gBrowser.tabpanels.addEventListener('mouseup', mouseUp, false);
            this.destructor = function() {
                gBrowser.tabpanels.removeEventListener('mouseup', mouseUp, false);
                if (w)
                    w.closeWin();
            };
            ucf_custom_script_win.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);
                };
                w.addEle1 = function(str, style) {
                    var ele = doc.createElementNS(xhtmlns, 'textarea');
                    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 = w.addEle1(text, 'display:block;border:1px solid #aaa;padding-bottom:3px;padding-left:3px;background-color:#fafcfe;color:#000;font:16px Times New Roman;width:310px;height:160px;overflow:auto;cursor:text;-moz-user-focus:normal;-moz-user-select:text;');
                cnt.contentEditable="true";
                cnt.context="contentAreaContextMenu";
                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);
                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, "<br />"));
                                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,'&amp;')+'" 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)+"&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/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABBUlEQVR4Ac2RMU4DMRREB2MqihQpAkUaqnAduuQw4Sx03CGcJYIiDYqQ0lCsZ77535ZFcgAkRuPvV7zd/dLiz3N1PFb8hmRckrfELZrF9ONQ1B6Yz0MyM7S0O6zGkVprh/3+Kw/JzkHSpRpJKZkpr9fYbOx0cjVsCbWG31oHBM9mtt0q73ZcrdLhAMlYQKkUI22aqsNo8HKZAMQhvVaKSHWj2Q2aPU3mJQFY7nuHyvYFduP83WF3AJRfcPNYnr/Lp1G1uK4m9sno1LaUbnX/htf8BNzoneUD5NhjvLCMhURQSQ93QCZwXYjFwg3I0NZKrvoknQPMIHkt/jRAQKMeG2yX89/mB4EJbKbZxIhFAAAAAElFTkSuQmCC");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|ru');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            menuItem = document.createXULElement("menuitem");
            menuItem.setAttribute("id", "context-en-google-translate");
            menuItem.setAttribute("label", "Перевести на английский");
            menuItem.setAttribute("class", "menuitem-iconic");
            menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAAB5UlEQVR4AWOgPZg0c9+Oq2+qpx9LaQaiw4mNB27efbs2uXFNQh2Q4Zm9zSNth23MhqjGnXMC86vnHmUS4udxv7OvOd2yPE7PTlfCTk9GVVEoyJA7WI8dyPA0k3U1l+jJMV7CeThpTZeoKDdDUsvBPSff/V+6/P/Bvf///2+bdvU/EKRm/k9IBNIlfZe+LFrzvbsbyJ636pKkyQyQhoUb7tZNvPpw3/0/TfX/ISAm5n94BIiRm/n/xYsLd946ei4vajoiqDuRAejQf//+o4PQ0P9+fmhiQGVnrr1kXJNYG2zEzXDxDsPv3wy/fkFJoOTPn39+/fr/69e/37//AUX+/mXRkO458wWHDba2f8wswCyQ3N+/f//8/fP7z5+TV18w2Mdt6plzPiptx5Wr7/+/ffMzOR6kysjkt74hWMPfp06O+2dulZCeFZKwnkE4m8E8bN3i9aCQ+dxY96GrK6bkGJD9R1v3l6Y20NVW9kt+/v//ZdbcFwkxTVPPMQimM8XEqkb7a/zoqLxkH9v4zVyI5+///wyMmtKMmhJAnbLqQjHxaw5r2orOmZN5uj470Zahat6BKS7JzpmLBHXm8GhM5lCdcP7ai1ZpixZxk9NXXjKIFzOIFjAI54oY1vXuue5qmscw+AAAW0tKxtPoicEAAAAASUVORK5CYII=");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|en');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu);
        }
    },
    specialwidgets: {
        _timer: null,
        get Customizable() {
            delete this.Customizable;
            if ("createSpecialWidget" in CustomizableUI)
                return this.Customizable = CustomizableUI;
            var scope = null;
            try {
                scope = Components.utils.import("resource:///modules/CustomizableUI.jsm", {}).CustomizableUIInternal;
            } catch (e) { }
            return this.Customizable = scope;
        },
        constructor: function() {
            if (!("CustomizableUI" in window) || !("gCustomizeMode" in window))
                return;
            ucf_custom_script_win.unloadlisteners.push("specialwidgets");
            window.addEventListener("customizationready", this, false);
        },
        destructor: function() {
            window.removeEventListener("customizationready", this, false);
        },
        handleEvent: function(event) {
            this[event.type](event);
        },
        customizationchange: function() {
            clearTimeout(this._timer);
            this._timer = setTimeout(() => {
                this.createSpecialWidgets();
            }, 1000);
        },
        customizationready: function() {
            if (!this.Customizable)
                return;
            this.createSpecialWidgets();
            window.addEventListener("customizationchange", this, false);
            window.addEventListener("customizationending", this, false);
        },
        customizationending: function() {
            window.removeEventListener("customizationchange", this, false);
            window.removeEventListener("customizationending", this, false);
        },
        createSpecialWidgets: function() {
            try {
                var fragment = document.createDocumentFragment();
                if (this.findSpecialWidgets("spring")) {
                    var spring = this.Customizable.createSpecialWidget("spring", document);
                    spring.setAttribute("label", "Растягивающийся интервал");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(spring, "palette"));
                }
                if (this.findSpecialWidgets("spacer")) {
                    var spacer = this.Customizable.createSpecialWidget("spacer", document);
                    spacer.setAttribute("label", "Интервал");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(spacer, "palette"));
                }
                if (this.findSpecialWidgets("separator")) {
                    var separator = this.Customizable.createSpecialWidget("separator", document);
                    separator.setAttribute("label", "Разделитель");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(separator, "palette"));
                }
                gCustomizeMode.visiblePalette.appendChild(fragment);
            } catch (e) {}
        },
        findSpecialWidgets: function(string) {
            try {
                if (!gCustomizeMode.visiblePalette.querySelector(`toolbar${string}[id^="customizableui-special-${string}"]`))
                    return true;
            } catch (e) {}
            return false;
        }
    },
    autohidesidebar: {
        sidebar: null,
        constructor: function() {
            var sidebar = this.sidebar = document.querySelector("#sidebar-box");
            if (!sidebar)
                return;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.addEventListener(type, this, false);
            });
            ucf_custom_script_win.unloadlisteners.push("autohidesidebar");
        },
        destructor: function() {
            var sidebar = this.sidebar;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.removeEventListener(type, this, false);
            });
        },
        handleEvent: function(event) {
            this[event.type](event);
        },
        dragenter: function() {
            if (!this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.setAttribute("sidebardrag", "true");
        },
        drop: function() {
            if (this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.removeAttribute("sidebardrag");
        },
        dragexit: function(event) {
            var sidebar = this.sidebar;
            var boxObj = sidebar.getBoundingClientRect(), boxScrn = !sidebar.boxObject ? sidebar : sidebar.boxObject;
            if ((!event.relatedTarget || event.screenY <= (boxScrn.screenY + 5) || event.screenY  >= (boxScrn.screenY + boxObj.height - 5)
                || event.screenX <= (boxScrn.screenX + 5) || event.screenX >= (boxScrn.screenX + boxObj.width - 5))
                && sidebar.hasAttribute("sidebardrag"))
                sidebar.removeAttribute("sidebardrag");
        }
    }
};

if (window.document.readyState != "complete") {
    window.addEventListener("load", function load() {
        window.removeEventListener("load", load, false);
        ucf_custom_script_win.load();
    }, false);
} else
    ucf_custom_script_win.load();

Отсутствует

 

№829221-04-2020 16:32:33

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06
не туда добавлено, ладно вот полный custom_script_win.js

скрытый текст

Выделить код

Код:

// Этот скрипт работает в главном окне браузера если включено в настройках

var ucf_custom_script_win = {
    initialized: false,
    unloadlisteners: [],
    load: function() {
        if (this.initialized)
            return;
        this.initialized = true;
        // this.specialwidgets.constructor(); // <-- Special Widgets
        this.autohidesidebar.constructor(); // <-- Auto Hide Sidebar
        /* ************************************************ */
        this.googletranslate.constructor();
        // Здесь может быть ваш код который сработает по событию "load" не раньше

        /* ************************************************ */
        if (this.unloadlisteners.length < 1)
            return;
        window.addEventListener("unload", this, false);
    },
    handleEvent: function(event) {
        this[event.type](event);
    },
    unload: function() {
        window.removeEventListener("unload", this, false);
        this.unloadlisteners.forEach((str) => {
            try {
                this[str].destructor();
            } catch (e) {}
        });
    },
    googletranslate: {
        constructor: function() {
            var lc = navigator.lastClick = {}, w = null, xhtmlns = 'http://www.w3.org/1999/xhtml';
            var mouseUp = function(e) {
                if (e.button) return;
                lc.X = e.screenX - mozInnerScreenX;
                lc.Y = e.screenY - mozInnerScreenY;
            };
            gBrowser.tabpanels.addEventListener('mouseup', mouseUp, false);
            this.destructor = function() {
                gBrowser.tabpanels.removeEventListener('mouseup', mouseUp, false);
                if (w)
                    w.closeWin();
            };
            ucf_custom_script_win.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);
                };
                w.addEle1 = function(str, style) {
                    var ele = doc.createElementNS(xhtmlns, 'textarea');
                    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 = w.addEle1(text, 'display:block;border:1px solid #aaa;padding-bottom:3px;padding-left:3px;background-color:#fafcfe;color:#000;font:16px Times New Roman;width:310px;height:160px;overflow:auto;cursor:text;-moz-user-focus:normal;-moz-user-select:text;');
                cnt.contentEditable="true";
                cnt.context="contentAreaContextMenu";
                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);
                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, "<br />"));
                                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,'&amp;')+'" 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)+"&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/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABBUlEQVR4Ac2RMU4DMRREB2MqihQpAkUaqnAduuQw4Sx03CGcJYIiDYqQ0lCsZ77535ZFcgAkRuPvV7zd/dLiz3N1PFb8hmRckrfELZrF9ONQ1B6Yz0MyM7S0O6zGkVprh/3+Kw/JzkHSpRpJKZkpr9fYbOx0cjVsCbWG31oHBM9mtt0q73ZcrdLhAMlYQKkUI22aqsNo8HKZAMQhvVaKSHWj2Q2aPU3mJQFY7nuHyvYFduP83WF3AJRfcPNYnr/Lp1G1uK4m9sno1LaUbnX/htf8BNzoneUD5NhjvLCMhURQSQ93QCZwXYjFwg3I0NZKrvoknQPMIHkt/jRAQKMeG2yX89/mB4EJbKbZxIhFAAAAAElFTkSuQmCC");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|ru');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            menuItem = document.createXULElement("menuitem");
            menuItem.setAttribute("id", "context-en-google-translate");
            menuItem.setAttribute("label", "Перевести на английский");
            menuItem.setAttribute("class", "menuitem-iconic");
            menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAAB5UlEQVR4AWOgPZg0c9+Oq2+qpx9LaQaiw4mNB27efbs2uXFNQh2Q4Zm9zSNth23MhqjGnXMC86vnHmUS4udxv7OvOd2yPE7PTlfCTk9GVVEoyJA7WI8dyPA0k3U1l+jJMV7CeThpTZeoKDdDUsvBPSff/V+6/P/Bvf///2+bdvU/EKRm/k9IBNIlfZe+LFrzvbsbyJ636pKkyQyQhoUb7tZNvPpw3/0/TfX/ISAm5n94BIiRm/n/xYsLd946ei4vajoiqDuRAejQf//+o4PQ0P9+fmhiQGVnrr1kXJNYG2zEzXDxDsPv3wy/fkFJoOTPn39+/fr/69e/37//AUX+/mXRkO458wWHDba2f8wswCyQ3N+/f//8/fP7z5+TV18w2Mdt6plzPiptx5Wr7/+/ffMzOR6kysjkt74hWMPfp06O+2dulZCeFZKwnkE4m8E8bN3i9aCQ+dxY96GrK6bkGJD9R1v3l6Y20NVW9kt+/v//ZdbcFwkxTVPPMQimM8XEqkb7a/zoqLxkH9v4zVyI5+///wyMmtKMmhJAnbLqQjHxaw5r2orOmZN5uj470Zahat6BKS7JzpmLBHXm8GhM5lCdcP7ai1ZpixZxk9NXXjKIFzOIFjAI54oY1vXuue5qmscw+AAAW0tKxtPoicEAAAAASUVORK5CYII=");
            menuItem.addEventListener("command", function() {ujs_google_translate('auto|en');}, false);
            contextMenu.insertBefore(menuItem, nextEleMenu);

            contextMenu.insertBefore(document.createXULElement("menuseparator"), nextEleMenu);
        }
    },
    specialwidgets: {
        _timer: null,
        get Customizable() {
            delete this.Customizable;
            if ("createSpecialWidget" in CustomizableUI)
                return this.Customizable = CustomizableUI;
            var scope = null;
            try {
                scope = Components.utils.import("resource:///modules/CustomizableUI.jsm", {}).CustomizableUIInternal;
            } catch (e) { }
            return this.Customizable = scope;
        },
        constructor: function() {
            if (!("CustomizableUI" in window) || !("gCustomizeMode" in window))
                return;
            ucf_custom_script_win.unloadlisteners.push("specialwidgets");
            window.addEventListener("customizationready", this, false);
        },
        destructor: function() {
            window.removeEventListener("customizationready", this, false);
        },
        handleEvent: function(event) {
            this[event.type](event);
        },
        customizationchange: function() {
            clearTimeout(this._timer);
            this._timer = setTimeout(() => {
                this.createSpecialWidgets();
            }, 1000);
        },
        customizationready: function() {
            if (!this.Customizable)
                return;
            this.createSpecialWidgets();
            window.addEventListener("customizationchange", this, false);
            window.addEventListener("customizationending", this, false);
        },
        customizationending: function() {
            window.removeEventListener("customizationchange", this, false);
            window.removeEventListener("customizationending", this, false);
        },
        createSpecialWidgets: function() {
            try {
                var fragment = document.createDocumentFragment();
                if (this.findSpecialWidgets("spring")) {
                    var spring = this.Customizable.createSpecialWidget("spring", document);
                    spring.setAttribute("label", "Растягивающийся интервал");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(spring, "palette"));
                }
                if (this.findSpecialWidgets("spacer")) {
                    var spacer = this.Customizable.createSpecialWidget("spacer", document);
                    spacer.setAttribute("label", "Интервал");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(spacer, "palette"));
                }
                if (this.findSpecialWidgets("separator")) {
                    var separator = this.Customizable.createSpecialWidget("separator", document);
                    separator.setAttribute("label", "Разделитель");
                    fragment.appendChild(gCustomizeMode.wrapToolbarItem(separator, "palette"));
                }
                gCustomizeMode.visiblePalette.appendChild(fragment);
            } catch (e) {}
        },
        findSpecialWidgets: function(string) {
            try {
                if (!gCustomizeMode.visiblePalette.querySelector(`toolbar${string}[id^="customizableui-special-${string}"]`))
                    return true;
            } catch (e) {}
            return false;
        }
    },
    autohidesidebar: {
        sidebar: null,
        constructor: function() {
            var sidebar = this.sidebar = document.querySelector("#sidebar-box");
            if (!sidebar)
                return;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.addEventListener(type, this, false);
            });
            ucf_custom_script_win.unloadlisteners.push("autohidesidebar");
        },
        destructor: function() {
            var sidebar = this.sidebar;
            ["dragenter", "drop", "dragexit"].forEach((type) => {
                sidebar.removeEventListener(type, this, false);
            });
        },
        handleEvent: function(event) {
            this[event.type](event);
        },
        dragenter: function() {
            if (!this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.setAttribute("sidebardrag", "true");
        },
        drop: function() {
            if (this.sidebar.hasAttribute("sidebardrag"))
            this.sidebar.removeAttribute("sidebardrag");
        },
        dragexit: function(event) {
            var sidebar = this.sidebar;
            var boxObj = sidebar.getBoundingClientRect(), boxScrn = !sidebar.boxObject ? sidebar : sidebar.boxObject;
            if ((!event.relatedTarget || event.screenY <= (boxScrn.screenY + 5) || event.screenY  >= (boxScrn.screenY + boxObj.height - 5)
                || event.screenX <= (boxScrn.screenX + 5) || event.screenX >= (boxScrn.screenX + boxObj.width - 5))
                && sidebar.hasAttribute("sidebardrag"))
                sidebar.removeAttribute("sidebardrag");
        }
    }
};

if (window.document.readyState != "complete") {
    window.addEventListener("load", function load() {
        window.removeEventListener("load", load, false);
        ucf_custom_script_win.load();
    }, false);
} else
    ucf_custom_script_win.load();

Огромнейшее спасибо Вам!!!
Можно попросить вас сделать еще вот эти кнопки

скрытый текст

Выделить код

Код:

// Искать в ... 
((searchSelect, popup) => addEventListener("popupshowing", {
    topic: "browser-search-engine-modified",
    defaultImg: "chrome://browser/skin/search-engine-placeholder.png",
    handleEvent(e) {
        if (searchSelect.hidden) return;

        var menu = document.createXULElement("menu");
        menu.className = "menu-iconic";
        menu.ePopup = menu.appendChild(document.createXULElement("menupopup"));
        menu.onclick = this.search;
        searchSelect.collapsed = true;
        searchSelect.before(menu);
        addDestructor(() => {
            menu.remove();
            searchSelect.collapsed = false;
            if (this.handleEvent == this.handler)
                Services.obs.removeObserver(this, this.topic);
        });
        this.handler = () => menu.hidden = searchSelect.hidden;
        this.handlerRebuild = () => this.handler() || this.rebuild(menu);
        this.rebuild(menu);
    },
    async rebuild(menu) {
        var de = Services.search.defaultEngine;
        de = de.wrappedJSObject || de;
        this.setAttrs(menu, de, `Искать в ${de.name} или в ...`);
        menu.ePopup.textContent = "";
        for(var engine of await Services.search.getVisibleEngines()) {
            if (engine == de) continue;
            var menuitem = document.createXULElement("menuitem");
            menuitem.className = "menuitem-iconic";
            this.setAttrs(menuitem, engine);
            menu.ePopup.append(menuitem);
        }
        this.handleEvent = this.handler;
        Services.obs.addObserver(this, this.topic, false);
    },
    setAttrs(node, engine, label = engine.name) {
        node.engine = engine;
        node.setAttribute("label", label);
        node.setAttribute("image", engine.iconURI ? engine.iconURI.spec : this.defaultImg);
    },
    observe() {
        this.handleEvent = this.handlerRebuild;
        Services.obs.removeObserver(this, this.topic);
    },
    search(e) {
        var {engine} = e.target;
        if (!engine) return;
        var submission = engine.getSubmission(
            searchSelect.searchTerms, null, "contextmenu"
        );
        submission && openLinkIn(submission.uri.spec, "tab", {
            postData: submission.postData,
            inBackground: e.button > 0,
            relatedToCurrent: true,
            triggeringPrincipal: searchSelect.principal
        });
        e.button != 1 && popup.state == "open" && popup.hidePopup();
    }
}, false, popup = searchSelect.closest("menupopup")))(
    document.getElementById("context-searchselect")
);

скрытый текст

Выделить код

Код:

/*Initialization Code*/
// Увеличить изображение ...
addEventListener("popupshowing", {
    imgZoom: 190,   // на сколько увеличить изображение из меню
    scrollZoom: 20, // на сколько увеличивать/уменьшать колесиком мыши
    scrollTop: 1,   // или -1, переключение направление прокрутки для увеличение колёсиком

    receiveMessage(msg) {
        var container = document.documentElement
            .appendChild(document.createElement("div"));
        addDestructor(() => container.remove());
        var image = container.appendChild(document.createXULElement("image"));
        image.style.cssText = "width: 100% !important; height: 100% !important;";
        image.setAttribute("validate", "never");

        var st = container.style;
        var dz = this.scrollZoom/100 * this.scrollTop;
        var currScale = 1, x, y, initialZoom = this.imgZoom/100 - 1;

        var hide, props = ["width", "height", "left", "top"], p = n => n + "px";
        var set = (...args) => props.forEach((prop, ind) => st[prop] = p(args[ind]));

        (hide = () => {
            st.cssText = "position: fixed; display: none; z-index: 2147483647;";
            currScale = 1;
            image.src = null;
        })();
        container.onwheel = (e, ds = e.deltaY > 0 ? -dz : dz) => {
            if (currScale < .15 && ds < 0) return;
            st.transform = `scale(${currScale += ds})`;
            var {width, height, left, top, bottom, right} = container.getBoundingClientRect();

            if (height < innerHeight) {
                if (top < 0) st.top = p(y -= top);
                if (bottom > innerHeight) st.top = p(y -= bottom - innerHeight);
            }
            if (width < innerWidth) {
                if (left < 0) st.left = p(x -= left);
                if (right > innerWidth) st.left = p(x -= right - innerWidth);
            }
        }
        (this.receiveMessage = msg => {
            var {src, width, height, left, top} = msg.data;
            image.src = src;
            left -= mozInnerScreenX;
            top -= mozInnerScreenY;

            set(width, height, x = left, y = top);
            st.display = "block";
            container.onwheel(null, initialZoom);
            window.addEventListener("mousedown", hide, {once: true, capture: true});
        })(msg);
    },
    handleEvent(e) {
        if (!gContextMenu.onImage) return;
        var menuitem = document.createXULElement("menuitem");
        menuitem.setAttribute("label", "Увеличить размер");
        menuitem.className = "menuitem-iconic";
        menuitem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADZElEQVR42oXSe0xbVRwH8N8597a35e7SAmUFukGhY66AMiNzw4GvTCQLCssc4pQsmTOa+ERMlrktW1zigpnEuWn8x2eMmiVGMBDCFjS+cJHEDIk8RoSNV1+3tLWX3t72nnO8sETJFrfvP7/k5Pw+Ob9fDoLrYi8ow9GFUbq+5aRLrGraqQcX6hlF2wkFEWn6EDIJAyQy9+3VT58cWb6PrmvmjGZS/FSHlxbXtbtLobGqJlPKMhNepWb0V8hKpi8FNd/gzCCogbdmvtg/8C9gz9+Eor5x5nn2tDOZ98Dx2i3C/uYai9mOGCxiDQIIg1/PgUCEhyvDMox9PXYBkPzaaoAzAFL0yle7ShtqO/eWJ9w1vJ1oGsVzYhTNATMQG4Q1G40ldDw6PB339fs7VgMmA0jnHfioo6F9Z3tDYYJzKSZKMYcDvAILiICfZUNYEYFixMKpKBk8MfTTasBsACnngU/6Wg4+VL/VFSOmBHAYY1BAhzAvgmyMEIkh0EUOBD1Eu49eStwA5D3z4TcPv9TYdHvxEhXSGgaEIMkJkKAS+ONmSKYolOVqMBlRSd8bv8v/AQXlJoiHUE5rZ1tFa/Nhj1uVrCaNMoQxYSaIqDxAGqAuQ2XZ1iS8HUTpkZMXe1eATOdtiCcJblGe1a3PnWp0uEvfv3tbeX5RhSet/q3wxh6xgAncZUmw2hxEryQx9/LHE7I2RV5HNudGFAtcZsuQd919u/kiz56JOwobcjd6xerqKnB4HIB4RvMzCM1DGj8X0GD64pL2Xdf850z+4djKC8wl24XUpj1P75sdfe/+sSHoq3uQnSuwa+s2Vy5uubd2jQWUTAYchJK8HpyIzvv7p/rMkV/OzPeeGEWi+x6LufiR573h8VO7Zr4n9fEZNeiqXHOofFvPsKPkS1fKsX5JU6uNZQh8Wh/hRcuvOC3/fLXrcGj52yOo7zzU9udvbzbN9uglggK2MhsnvfiE0tY9tfed7vM98D+x53tx1DdG0Z2b97Ejf3SRSiGGCysyENvdoipZa4+/8NmPp8+N+Ei2ZEVpQhG71rdcqFFozD+xcoQugFUvlDS8wWsl8Uebk5C79ujjHwyc6R/309ysDBRauEzhJkG9ErAdG0xEe6yVkwqcr+549/zZgcmQ7pAEkH2TDG6RfwCoJI0uEWJP5QAAAABJRU5ErkJggg==");
        menuitem.setAttribute("oncommand", "handleCommand();");
        e.target.append(menuitem);
        addDestructor(() => menuitem.remove());
        menuitem.handleCommand = () => this.cmd();

        this.handleEvent = () => menuitem.hidden = !gContextMenu.onImage;
    },
    cmd() {
        var msg = "CB:GetImageScreenRectForMosuseZoom";
        var code = `(targetIdentifier => {

            var image = ChromeUtils.import("resource://gre/modules/ContentDOMReference.jsm")
                .ContentDOMReference.resolve(targetIdentifier);

            var mm = image.ownerGlobal.docShell.messageManager;
            var bu = mm.BrowserUtils || ChromeUtils
                .import("resource://gre/modules/BrowserUtils.jsm").BrowserUtils;

            mm.sendAsyncMessage("${msg}", Object.assign(
                {src: image.currentSrc}, bu.getElementBoundingScreenRect(image)
            ));
        })(`;
        messageManager.addMessageListener(msg, this);
        addDestructor(() => messageManager.removeMessageListener(msg, this));

        (this.cmd = () => {
            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(
                code + JSON.stringify(gContextMenu.targetIdentifier) + ")"
            ), false);
        })();
    }
}, false, document.getElementById("contentAreaContextMenu") || 1);

Отсутствует

 

№829321-04-2020 18:46:56

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06
попробуйте пока вторую добавить в custom_script_win.js
ucf_custom_script_win.load

скрытый текст

Выделить код

Код:

(this.ucf_img_scroll_zoom = {
            imgZoom: 190,   // на сколько увеличить изображение из меню
            scrollZoom: 20, // на сколько увеличивать/уменьшать колесиком мыши
            scrollTop: 1,   // или -1, переключение направление прокрутки для увеличение колёсиком
            init(that) {
                var popup = this.popup = document.querySelector("#contentAreaContextMenu");
                if (!popup) return;
                popup.addEventListener("popupshowing", this);
                that.unloadlisteners.push("ucf_img_scroll_zoom");
            },
            receiveMessage(msg) {
                var container = document.documentElement
                    .appendChild(document.createElement("div"));
                var image = container.appendChild(document.createXULElement("image"));
                image.style.cssText = "width: 100% !important; height: 100% !important;";
                image.setAttribute("validate", "never");

                var st = container.style;
                var dz = this.scrollZoom/100 * this.scrollTop;
                var currScale = 1, x, y, initialZoom = this.imgZoom/100 - 1;

                var hide, props = ["width", "height", "left", "top"], p = n => n + "px";
                var set = (...args) => props.forEach((prop, ind) => st[prop] = p(args[ind]));

                (hide = () => {
                    st.cssText = "position: fixed; display: none; z-index: 2147483647;";
                    currScale = 1;
                    image.src = null;
                })();
                container.onwheel = (e, ds = e.deltaY > 0 ? -dz : dz) => {
                    if (currScale < .15 && ds < 0) return;
                    st.transform = `scale(${currScale += ds})`;
                    var {width, height, left, top, bottom, right} = container.getBoundingClientRect();

                    if (height < innerHeight) {
                        if (top < 0) st.top = p(y -= top);
                        if (bottom > innerHeight) st.top = p(y -= bottom - innerHeight);
                    }
                    if (width < innerWidth) {
                        if (left < 0) st.left = p(x -= left);
                        if (right > innerWidth) st.left = p(x -= right - innerWidth);
                    }
                }
                (this.receiveMessage = msg => {
                    var {src, width, height, left, top} = msg.data;
                    image.src = src;
                    left -= mozInnerScreenX;
                    top -= mozInnerScreenY;

                    set(width, height, x = left, y = top);
                    st.display = "block";
                    container.onwheel(null, initialZoom);
                    window.addEventListener("mousedown", hide, {once: true, capture: true});
                })(msg);
            },
            handleEvent(e) {
                if (!gContextMenu.onImage) return;
                var menuitem = document.createXULElement("menuitem");
                menuitem.setAttribute("label", "Увеличить размер");
                menuitem.className = "menuitem-iconic";
                menuitem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADZElEQVR42oXSe0xbVRwH8N8597a35e7SAmUFukGhY66AMiNzw4GvTCQLCssc4pQsmTOa+ERMlrktW1zigpnEuWn8x2eMmiVGMBDCFjS+cJHEDIk8RoSNV1+3tLWX3t72nnO8sETJFrfvP7/k5Pw+Ob9fDoLrYi8ow9GFUbq+5aRLrGraqQcX6hlF2wkFEWn6EDIJAyQy9+3VT58cWb6PrmvmjGZS/FSHlxbXtbtLobGqJlPKMhNepWb0V8hKpi8FNd/gzCCogbdmvtg/8C9gz9+Eor5x5nn2tDOZ98Dx2i3C/uYai9mOGCxiDQIIg1/PgUCEhyvDMox9PXYBkPzaaoAzAFL0yle7ShtqO/eWJ9w1vJ1oGsVzYhTNATMQG4Q1G40ldDw6PB339fs7VgMmA0jnHfioo6F9Z3tDYYJzKSZKMYcDvAILiICfZUNYEYFixMKpKBk8MfTTasBsACnngU/6Wg4+VL/VFSOmBHAYY1BAhzAvgmyMEIkh0EUOBD1Eu49eStwA5D3z4TcPv9TYdHvxEhXSGgaEIMkJkKAS+ONmSKYolOVqMBlRSd8bv8v/AQXlJoiHUE5rZ1tFa/Nhj1uVrCaNMoQxYSaIqDxAGqAuQ2XZ1iS8HUTpkZMXe1eATOdtiCcJblGe1a3PnWp0uEvfv3tbeX5RhSet/q3wxh6xgAncZUmw2hxEryQx9/LHE7I2RV5HNudGFAtcZsuQd919u/kiz56JOwobcjd6xerqKnB4HIB4RvMzCM1DGj8X0GD64pL2Xdf850z+4djKC8wl24XUpj1P75sdfe/+sSHoq3uQnSuwa+s2Vy5uubd2jQWUTAYchJK8HpyIzvv7p/rMkV/OzPeeGEWi+x6LufiR573h8VO7Zr4n9fEZNeiqXHOofFvPsKPkS1fKsX5JU6uNZQh8Wh/hRcuvOC3/fLXrcGj52yOo7zzU9udvbzbN9uglggK2MhsnvfiE0tY9tfed7vM98D+x53tx1DdG0Z2b97Ejf3SRSiGGCysyENvdoipZa4+/8NmPp8+N+Ei2ZEVpQhG71rdcqFFozD+xcoQugFUvlDS8wWsl8Uebk5C79ujjHwyc6R/309ysDBRauEzhJkG9ErAdG0xEe6yVkwqcr+549/zZgcmQ7pAEkH2TDG6RfwCoJI0uEWJP5QAAAABJRU5ErkJggg==");
                menuitem.setAttribute("oncommand", "handleCommand();");
                e.target.append(menuitem);
                menuitem.handleCommand = () => this.cmd();

                this.handleEvent = () => menuitem.hidden = !gContextMenu.onImage;
            },
            cmd() {
                var msg = this.msg = "UCF:GetImageScreenRectForMosuseZoom";
                var code = `(targetIdentifier => {
                    var image = ChromeUtils.import("resource://gre/modules/ContentDOMReference.jsm")
                        .ContentDOMReference.resolve(targetIdentifier);
                    var mm = image.ownerGlobal.docShell.messageManager;
                    var rect = image.getBoundingClientRect();
                    var win = image.ownerGlobal;
                    var x = rect.left, y = rect.top;
                    var parentFrame = win.frameElement;
                    while (parentFrame) {
                      win = parentFrame.ownerGlobal;
                      let cstyle = win.getComputedStyle(parentFrame);
                      let framerect = parentFrame.getBoundingClientRect();
                      x +=
                        framerect.left +
                        parseFloat(cstyle.borderLeftWidth) +
                        parseFloat(cstyle.paddingLeft);
                      y +=
                        framerect.top +
                        parseFloat(cstyle.borderTopWidth) +
                        parseFloat(cstyle.paddingTop);
                      parentFrame = win.frameElement;
                    }
                      x += win.mozInnerScreenX;
                      y += win.mozInnerScreenY;
                    var fullZoom = win.windowUtils.fullZoom;
                    mm.sendAsyncMessage("${msg}",
                        {
                            src: image.currentSrc,
                            left: x * fullZoom,
                            top: y * fullZoom,
                            width: rect.width * fullZoom,
                            height: rect.height * fullZoom,
                        }
                    );
                })(`;
                messageManager.addMessageListener(msg, this);

                (this.cmd = () => {
                    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(
                        code + JSON.stringify(gContextMenu.targetIdentifier) + ")"
                    ), false);
                })();
            },
            destructor() {
                this.popup.removeEventListener("popupshowing", this);
                if (this.msg)
                    messageManager.removeMessageListener(this.msg, this);
            },
        }).init(this);

Отредактировано Vitaliy V. (11-03-2021 20:55:22)

Отсутствует

 

№829421-04-2020 19:02:17

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06
попробуйте пока вторую добавить в custom_script_win.js
ucf_custom_script_win

или опять полностью?

Спасибо!!! эта получилась
было бы совсем хорошо  еслибы вы еще кнопку дополнений переделали бы для user_chrome_files

иконка

скрытый текст

Выделить код

Код:

data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsSAAALEgHS3X78AAAAs0lEQVR42u2XwQ6AIAiGcb5Ah16z9z9Sbrm5JogJuJVsXDr4fwk/KoAgEBH2Y8My07crAlhHTfwBYRuUeM7vA0wvQaMJfwCQhCgAFQiuxqMpArQSF7tkASyAmrUo65kAZKHbMlHbotNnRDkLyvVEM0ILgJum06akqEQuANZN2ASwtmEXgNWJyDahBwBjwwC9f9FbouGzgPOqBGIBaAHU3oDRBYDaBbcmpBZyvRW/2QHpu+EEmA4rarrrhC0AAAAASUVORK5CYII=

скрытый текст

Выделить код

Код:

// http://infocatcher.ucoz.net/js/cb/toggleRestartlessAddons.js
// https://forum.mozilla-russia.org/viewtopic.php?id=57948
// https://github.com/Infocatcher/Custom_Buttons/tree/master/Toggle_Restartless_Add-ons

// Toggle Restartless Add-ons button for Custom Buttons
// (code for "initialization" section)
// Also the code can be used from main window context (as Mouse Gestures code, for example)

// Also you can check for add-ons updates using right-click:
// copy all code from
// https://github.com/Infocatcher/Custom_Buttons/blob/master/Check_for_Addons_Updates/checkForAddonsUpdates.js
// after "//== Check for Addons Updates begin"

// See "var style = " to modify styles for specific add-ons

// (c) Infocatcher 2013-2019
// version 0.1.3pre4 - 2020-01-01

var options = {
	addonTypes: ["extension", "plugin"],
	// Possible values: "extension", "plugin"
	// From extensions: "userstyle" (Stylish), "greasemonkey-user-script" (Greasemonkey), "userscript" (Scriptish)
	// (swap to reorder in the menu)
	showVersions: 0,
	// 0 - don't show versions
	// 1 - show after name: "Addon Name 1.2"
	// 2 - show as "acceltext" (in place for hotkey text)
	showHidden: 1,
	// 0  - don't show hidden add-ons
	// -1 - show only enabled hidden add-ons (e.g. to track new items)
	// 1  - show all hidden add-ons
	sort: {
		enabled:     0,
		clickToPlay: 0,
		disabled:    1
		// Sort order:
		// 0, 0, 0 - sort add-ons of each type alphabetically
		// 0, 0, 1 - show enabled add-ons (of each type) first
		// 0, 1, 2 - enabled add-ons, then click-to-play and then disabled
	},
	closeMenu: false, // Close menu after left-click
	closeMenuClickToPlay: false // Close menu after left-click, for click to play plugins
	// Use Shift+click to invert closeMenu* behavior
};

var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

var mp = document.createElementNS(xulns, "menupopup");
mp.setAttribute("onpopupshowing", "this.updateMenu();");
mp.setAttribute("oncommand", "this.handleEvent(event);");
mp.setAttribute("onmousedown", "if(event.button == 0) this.handleEvent(event);");
mp.setAttribute("onclick", "if(event.button > 0) this.handleEvent(event);");
mp.setAttribute("oncontextmenu", "return false;");
mp.setAttribute("onpopuphidden", "this.destroyMenu();");

var tb = this.parentNode;
if(tb && tb.getAttribute("orient") == "vertical") {
	// https://addons.mozilla.org/firefox/addon/vertical-toolbar/
	var isRight = tb.parentNode.getAttribute("placement") == "right";
	mp.setAttribute("position", isRight ? "start_before" : "end_before");
}

var cleanupTimer = 0;
mp.updateMenu = function() {
	clearTimeout(cleanupTimer);
	addStyle();
	getRestartlessAddons(options.addonTypes, function(addons) {
		var df = document.createDocumentFragment();
		var prevType;
		function sortPosition(addon) {
			if("STATE_ASK_TO_ACTIVATE" in AddonManager && addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE)
				return options.sort.clickToPlay;
			if(addon.isActive)
				return options.sort.enabled;
			return options.sort.disabled;
		}
		function key(addon) {
			return options.addonTypes.indexOf(addon.type)
				+ "\n" + sortPosition(addon)
				+ "\n" + addon.name.toLowerCase();
		}
		addons.sort(function(a, b) {
			var ka = key(a);
			var kb = key(b);
			return ka == kb ? 0 : ka < kb ? -1 : 1;
		}).forEach(function(addon) {
			var type = addon.type;
			if(prevType && type != prevType)
				df.appendChild(document.createElementNS(xulns, "menuseparator"));
			prevType = type;
			var icon = addon.iconURL || addon.icon64URL;
			var mi = document.createElementNS(xulns, "menuitem");
			mi.className = "menuitem-iconic";
			var label = addon.name;
			if(options.showVersions == 1)
				label += " " + addon.version;
			else if(options.showVersions == 2)
				mi.setAttribute("acceltext", addon.version);
			mi.setAttribute("label", label);
			mi.setAttribute("image", icon || mp.icons[type] || "");
			if(!icon && mp.icons.useSVG)
				mi.style.fill = "#15c";
			var tip = addon.description || "";
			var delay = "delayedStartupAddons" in Services
				&& Services.delayedStartupAddons[addon.id] || null;
			var isDelayed = delay !== null;
			mi.classList.toggle("toggleRestartlessAddons-isDelayed", isDelayed);
			if(isDelayed)
				tip = "[Delayed Startup: " + delay.toLocaleString() + "]" + (tip ? "\n" + tip : "");
			tip && mi.setAttribute("tooltiptext", tip);
			mi.classList.toggle("toggleRestartlessAddons-isHidden", addon.hidden || false);
			setDisabled(mi, addon.userDisabled);
			mi._cbAddon = addon;
			df.appendChild(mi);
		});
		mp.textContent = "";
		mp.appendChild(df);
	});
};
mp.handleEvent = function(e) {
	var mi = e.target;
	if(!("_cbAddon" in mi))
		return;
	var addon = mi._cbAddon;
	if(e.type == "mousedown") {
		var closeMenu = isAskToActivateAddon(addon)
			? options.closeMenuClickToPlay
			: options.closeMenu;
		if(e.shiftKey)
			closeMenu = !closeMenu;
		mi.setAttribute("closemenu", closeMenu ? "auto" : "none");
		return;
	}
	var hasMdf = hasModifier(e);
	if(e.type == "command" && (!hasMdf || e.shiftKey)) {
		let newDis = setNewDisabled(addon);
		setDisabled(mi, newDis);
	}
	else if(e.type == "command" && hasMdf || e.type == "click" && e.button == 1) {
		openAddonPage(addon);
		closeMenus(mi);
	}
	else if(e.type == "click" && e.button == 2) {
		if(openAddonOptions(addon))
			closeMenus(mi);
	}
};
mp.destroyMenu = function() {
	removeStyle();
	clearTimeout(cleanupTimer);
	cleanupTimer = setTimeout(function() {
		mp.textContent = "";
	}, 5000);
};
mp.icons = {
	get platformVersion() {
		delete this.platformVersion;
		return this.platformVersion = parseFloat(Services.appinfo.platformVersion);
	},
	get useSVG() {
		delete this.useSVG;
		return this.useSVG = Services.appinfo.name == "Firefox" && this.platformVersion >= 57;
	},
	get plugin() {
		delete this.plugin;
		return this.plugin = this.useSVG
			? this.platformVersion >= 65
				? "chrome://global/skin/plugins/pluginGeneric.svg"
				: "chrome://mozapps/skin/plugins/pluginGeneric.svg"
			: "chrome://mozapps/skin/plugins/pluginGeneric-16.png";
	},
	get extension() {
		delete this.extension;
		return this.extension = this.useSVG
			? this.platformVersion >= 76
				? "chrome://mozapps/skin/extensions/extensionGeneric.svg" // Or chrome://mozapps/skin/extensions/extension.svg
				: "chrome://mozapps/skin/extensions/extensionGeneric-16.svg"
			: "chrome://mozapps/skin/extensions/extensionGeneric-16.png";
	}
};
function isAskToActivateAddon(addon) {
	return addon.type == "plugin"
		&& "STATE_ASK_TO_ACTIVATE" in AddonManager
		&& Services.prefs.getBoolPref("plugins.click_to_play", true);
}
function setNewDisabled(addon) {
	var newDis = getNewDisabled(addon);
	var oldDis = addon.userDisabled;
	try {
		addon.userDisabled = newDis;
	}
	catch(e) { // Error: Cannot disable hidden add-on firefox@getpocket.com
		_log("Can't set addon.userDisabled to " + newDis + ", error:\n" + e);
		if(addon.hidden)
			setNewDisabledRaw(addon, newDis);
	}
	var realDis = addon.userDisabled;
	if(realDis != newDis && addon.type == "extension") { // Firefox 62+? Weird things happens
		setNewDisabledRaw(addon, newDis);
		realDis = addon.userDisabled;
	}
	if(realDis != newDis) { // We can't enable vulnerable plugins
		let err = "Can't set addon.userDisabled to " + newDis + ", real value: " + realDis;
		if(newDis) {
			_log(err + "\nSTATE_ASK_TO_ACTIVATE not supported?");
			newDis = false;
		}
		else {
			_log(err + "\nVulnerable plugin?");
			if(oldDis == AddonManager.STATE_ASK_TO_ACTIVATE)
				newDis = true;
			else
				newDis = AddonManager.STATE_ASK_TO_ACTIVATE;
		}
		addon.userDisabled = newDis;
	}
	ensureSpecialDisabled(addon, newDis);
	return addon.userDisabled;
}
function getNewDisabled(addon) {
	// disabled -> STATE_ASK_TO_ACTIVATE -> enabled -> ...
	var curDis = addon.userDisabled;
	var newDis;
	if("STATE_ASK_TO_ACTIVATE" in AddonManager && curDis == AddonManager.STATE_ASK_TO_ACTIVATE)
		newDis = false;
	else if(!curDis)
		newDis = true;
	else {
		if(isAskToActivateAddon(addon))
			newDis = AddonManager.STATE_ASK_TO_ACTIVATE;
		else
			newDis = false;
	}
	return newDis;
}
function setNewDisabledRaw(addon, newDis) {
	_log("Let's try set addon.userDisabled using raw hack");
	let g = Components.utils.import("resource://gre/modules/addons/XPIProvider.jsm", {});
	if("XPIDatabase" in g && "updateAddonDisabledState" in g.XPIDatabase) { // Firefox 61+
		let rawAddon = g.XPIDatabase.getAddons().find(function(rawAddon) {
			return rawAddon.id == addon.id;
		});
		g.XPIDatabase.updateAddonDisabledState(
			rawAddon,
			g.XPIDatabase.updateAddonDisabledState.length == 1 // Firefox 74+
				? { userDisabled: newDis }
				: newDis
		);
	}
	else if("eval" in g) { // See "set userDisabled(val)"
		let addonFor = g.eval("addonFor");
		let rawAddon = addonFor(addon);
		//rawAddon.userDisabled = newDis;
		g.XPIProvider.updateAddonDisabledState(rawAddon, newDis);
	}
	else { // Firefox 57+? See https://forum.mozilla-russia.org/viewtopic.php?pid=745272#p745272
		updateAddonDisabledState(addon, newDis);
	}
}
function updateAddonDisabledState(addon, newDis) {
	var nsvo = Components.utils.import("resource://gre/modules/addons/XPIProvider.jsm", {});
	var key = "_cbToggleRestartlessAddonsData";
	var url = URL.createObjectURL(new Blob([
		"XPIProvider.updateAddonDisabledState(addonFor(this." + key + "[0]), this." + key + "[1]); delete this." + key + ";"
	]));
	addDestructor(function() {
		URL.revokeObjectURL(url);
	});
	(updateAddonDisabledState = function(addon, newDis) {
		nsvo[key] = [addon, newDis];
		Services.scriptloader.loadSubScript(url, nsvo);
	})(addon, newDis);
}
function setDisabled(mi, disabled) {
	var askToActivate = "STATE_ASK_TO_ACTIVATE" in AddonManager && disabled == AddonManager.STATE_ASK_TO_ACTIVATE;
	var cl = mi.classList;
	cl.toggle("toggleRestartlessAddons-askToActivate", askToActivate);
	cl.toggle("toggleRestartlessAddons-disabled", disabled && !askToActivate);
}
function ensureSpecialDisabled(addon, newDis) {
	if(addon.id == "screenshots@mozilla.org")
		Services.prefs.setBoolPref("extensions.screenshots.disabled", newDis);
}

if(
	this instanceof XULElement // Custom Buttons
	&& typeof event == "object"
	&& !("type" in event) && typeof _phase == "string" && _phase == "init" // Initialization
) {
	this.type = "menu";
	this.orient = "horizontal";
	this.appendChild(mp);

	this.onmouseover = function(e) {
		if(e.target != this)
			return;
		Array.prototype.some.call(
			this.parentNode.getElementsByTagName("*"),
			function(node) {
				if(
					node != this
					&& node.namespaceURI == xulns
					// See https://github.com/Infocatcher/Custom_Buttons/issues/28
					//&& node.boxObject
					//&& node.boxObject instanceof Components.interfaces.nsIMenuBoxObject
					&& "open" in node
					&& node.open
					&& node.getElementsByTagName("menupopup").length
				) {
					node.open = false;
					this.open = true;
					return true;
				}
				return false;
			},
			this
		);
	};
	this.onmousedown = function(e) {
		if(e.target == this && e.button == 0 && hasModifier(e))
			e.preventDefault();
	};
	this.oncontextmenu = function(e) {
		if(e.target == this && !hasModifier(e) && hasUpdater())
			e.preventDefault();
	};
	this.onclick = function(e) {
		if(e.target != this)
			return;
		if(e.button == 0 && hasModifier(e) || e.button == 1)
			openAddonsManager();
		else if(e.button == 2 && !hasModifier(e) && hasUpdater())
			checkForAddonsUpdates.call(this);
	};
}
else { // Mouse gestures or something other...
	let e;
	if(typeof event == "object" && event instanceof Event && "screenX" in event) // FireGestures
		e = event;
	else if(
		this instanceof Components.interfaces.nsIDOMChromeWindow
		&& "mgGestureState" in window && "endEvent" in mgGestureState // Mouse Gestures Redox
	)
		e = mgGestureState.endEvent;
	else {
		let anchor = this instanceof XULElement && this
			|| window.gBrowser && gBrowser.selectedBrowser
			|| document.documentElement;
		if("boxObject" in anchor) {
			let bo = anchor.boxObject;
			e = {
				screenX: bo.screenX,
				screenY: bo.screenY
			};
			if(this instanceof XULElement)
				e.screenY += bo.height;
		}
	}
	if(!e || !("screenX" in e))
		throw new Error("[Toggle Restartless Add-ons]: Can't get event object");
	document.documentElement.appendChild(mp);
	mp.addEventListener("popuphidden", function destroy(e) {
		mp.removeEventListener(e.type, destroy, false);
		setTimeout(function() {
			mp.destroyMenu();
			mp.parentNode.removeChild(mp);
		}, 0);
	}, false);
	mp.openPopupAtScreen(e.screenX, e.screenY);
}

function getRestartlessAddons(addonTypes, callback, context) {
	if(!("AddonManager" in window))
		Components.utils.import("resource://gre/modules/AddonManager.jsm");
	if(!("Services" in window))
		Components.utils.import("resource://gre/modules/Services.jsm");
	var then, promise = AddonManager.getAddonsByTypes(addonTypes, then = function(addons) {
		callback.call(context, addons.filter(function(addon) {
			var ops = addon.operationsRequiringRestart;
			return !addon.appDisabled
				&& !(ops & AddonManager.OP_NEEDS_RESTART_ENABLE || ops & AddonManager.OP_NEEDS_RESTART_DISABLE)
				&& (
					!addon.hidden
					|| options.showHidden > 0
					|| options.showHidden == -1 && !addon.userDisabled
				)
				&& (addon.iconURL || "").substr(0, 29) != "resource://search-extensions/";
		}));
	});
	promise && typeof promise.then == "function" && promise.then(then, Components.utils.reportError); // Firefox 61+
}
function openAddonOptions(addon) {
	// Based on code from chrome://mozapps/content/extensions/extensions.js
	// Firefox 21.0a1 (2013-01-27)
	var optionsURL = addon.optionsURL;
	if(!addon.isActive || !optionsURL)
		return false;
	if(addon.type == "plugin") // No options for now!
		return false;
	if(
		addon.optionsType == (AddonManager.OPTIONS_TYPE_INLINE || NaN)
		|| addon.optionsType == (AddonManager.OPTIONS_TYPE_INLINE_INFO || NaN)
		|| addon.optionsType == (AddonManager.OPTIONS_TYPE_INLINE_BROWSER || NaN)
	)
		openAddonPage(addon, true);
	else if(addon.optionsType == AddonManager.OPTIONS_TYPE_TAB && "switchToTabHavingURI" in window)
		switchToTabHavingURI(optionsURL, true);
	else {
		let windows = Services.wm.getEnumerator(null);
		while(windows.hasMoreElements()) {
			let win = windows.getNext();
			if(win.document.documentURI == optionsURL) {
				win.focus();
				return true;
			}
		}
		// Note: original code checks browser.preferences.instantApply and may open modal windows
		window.openDialog(optionsURL, "", "chrome,titlebar,toolbar,centerscreen,dialog=no");
	}
	return true;
}
function openAddonsManager(view) {
	var openAddonsMgr = window.BrowserOpenAddonsMgr // Firefox
		|| window.openAddonsMgr // Thunderbird
		|| window.toEM; // SeaMonkey
	openAddonsMgr(view);
}
function openAddonPage(addon, scrollToPreferences) {
	var platformVersion = parseFloat(
		Services.appinfo.name == "Pale Moon"
			? Services.appinfo.version
			: Services.appinfo.platformVersion
	);
	scrollToPreferences = scrollToPreferences && platformVersion >= 12
		? "/preferences"
		: "";
	openAddonsManager("addons://detail/" + encodeURIComponent(addon.id) + scrollToPreferences);
}

function hasModifier(e) {
	return e.ctrlKey || e.shiftKey || e.altKey || e.metaKey;
}

function addStyle() {
	if(addStyle.hasOwnProperty("_style"))
		return;
	var style = '\
		.toggleRestartlessAddons-isDelayed > .menu-iconic-text {\n\
			opacity: 0.75;\n\
			color: #070;\n\
		}\n\
		.toggleRestartlessAddons-isHidden > .menu-iconic-text {\n\
			color: #609;\n\
		}\n\
		.toggleRestartlessAddons-disabled > .menu-iconic-left {\n\
			opacity: 0.4;\n\
		}\n\
		.toggleRestartlessAddons-disabled > .menu-iconic-text,\n\
		.toggleRestartlessAddons-disabled > .menu-accel-container {\n\
			opacity: 0.5;\n\
		}\n\
		.toggleRestartlessAddons-askToActivate {\n\
			color: -moz-nativehyperlinktext;\n\
		}';
	addStyle._style = document.insertBefore(
		document.createProcessingInstruction(
			"xml-stylesheet",
			'href="' + "data:text/css,"
				+ encodeURIComponent(style) + '" type="text/css"'
		),
		document.documentElement
	);
}
function removeStyle() {
	if(!addStyle.hasOwnProperty("_style"))
		return;
	var s = addStyle._style;
	s.parentNode.removeChild(s);
	delete addStyle._style;
}
function closeMenus(node) {
	// Based on function closeMenus from chrome://browser/content/utilityOverlay.js
	for(; node && "tagName" in node; node = node.parentNode) {
		if(
			node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
			&& (node.localName == "menupopup" || node.localName == "popup")
		)
			node.hidePopup();
	}
}
function _log(s) {
	if(typeof LOG == "function") // Custom Buttons
		LOG(s);
	else // Or something else
		Services.console.logStringMessage("Toggle Restartless Add-ons: " + s);
}

function hasUpdater() {
	var has = checkForAddonsUpdates.toString().indexOf("about:addons") != -1;
	hasUpdater = function() {
		return has;
	};
	return has;
}
function checkForAddonsUpdates() {
//== Check for Addons Updates begin
// http://infocatcher.ucoz.net/js/cb/checkForAddonsUpdates.js
// https://forum.mozilla-russia.org/viewtopic.php?id=57958
// https://github.com/Infocatcher/Custom_Buttons/tree/master/Check_for_Addons_Updates

// Check for Addons Updates button for Custom Buttons
// (code for "code" section)

// (c) Infocatcher 2012-2020
// version 0.1.6pre - 2020-01-24

// Button just open hidden tab with about:addons and trigger built-in "Check for Updates" function.
// And show tab, if found updates.

(function() {
var btn = this instanceof XULElement
	? this
	: { // Launched not from custom button
		image: "", // Base64-encoded icon (if empty, will be used "imgLoading")
		label: "Check for Addons Updates",
		tooltipText: ""
	};
if("_cb_disabled" in btn)
	return;
btn._cb_disabled = true;

if(!("Services" in window))
	Components.utils.import("resource://gre/modules/Services.jsm");
var app = Services.appinfo.name;

var ADDONS_URL = "about:addons";

var progressIcon = new ProgressIcon(btn);
var image = btn.image || progressIcon.imgLoading;
var tip = btn.tooltipText;
btn.tooltipText = "Open " + ADDONS_URL + "…";

var tab, browser, gBrowser;
var tbTabInfo, tbTab;

var trgWindow = Services.wm.getMostRecentWindow("navigator:browser")
	|| app == "Thunderbird" && Services.wm.getMostRecentWindow("mail:3pane")
	|| window;
var trgDocument = trgWindow.document;
var tabmail = trgDocument.getElementById("tabmail");

if(tabmail && app == "Thunderbird") { // Note: SeaMonkey doesn't support content tabs in mail window
	let addonsWin;
	let receivePong = function(subject, topic, data) {
		addonsWin = subject;
	};
	Services.obs.addObserver(receivePong, "EM-pong", false);
	Services.obs.notifyObservers(null, "EM-ping", "");
	Services.obs.removeObserver(receivePong, "EM-pong");
	if(addonsWin) {
		let rootWindow = addonsWin
			.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
			.getInterface(Components.interfaces.nsIWebNavigation)
			.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
			.rootTreeItem
			.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
			.getInterface(Components.interfaces.nsIDOMWindow);
		tabmail = rootWindow.document.getElementById("tabmail");
		tbTabInfo = tabmail.getBrowserForDocument(addonsWin);
		tbTab = tab = tbTabInfo.tabNode;
		processAddonsTab(addonsWin);
	}
	else {
		Services.obs.addObserver(function observer(subject, topic, data) {
			Services.obs.removeObserver(observer, topic);
			if(subject.document.readyState == "complete")
				processAddonsTab(subject);
			else {
				subject.addEventListener("load", function onLoad(e) {
					subject.removeEventListener(e.type, onLoad, false);
					processAddonsTab(subject);
				}, false);
			}
		}, "EM-loaded", false);
		// See openAddonsMgr() -> openContentTab()
		tbTabInfo = tabmail.openTab("contentTab", {
			contentPage: ADDONS_URL,
			clickHandler: "specialTabs.siteClickHandler(event, /addons\.mozilla\.org/);",
			background: true
		});
		tbTab = tab = tbTabInfo.tabNode;
		tbTab.collapsed = true;
		// Note: dontSelectHiddenTab() not implemented
	}
}
else if("gBrowser" in trgWindow && trgWindow.gBrowser.tabs) {
	let isPending = false;
	let ws = Services.wm.getEnumerator("navigator:browser");
	windowsLoop:
	while(ws.hasMoreElements()) {
		let w = ws.getNext();
		let tabs = w.gBrowser.tabs;
		for(let i = 0, l = tabs.length; i < l; ++i) {
			let t = tabs[i];
			if(
				!t.closing
				&& t.linkedBrowser
				&& t.linkedBrowser.currentURI.spec == ADDONS_URL
			) {
				tab = t;
				break windowsLoop;
			}
		}
	}

	gBrowser = trgWindow.gBrowser;
	if(!tab) {
		tab = gBrowser.addTab(ADDONS_URL, {
			triggeringPrincipal: "Services" in window // Firefox 63+
				&& Services.scriptSecurityManager
				&& Services.scriptSecurityManager.getSystemPrincipal()
		});
		tab.collapsed = true;
		tab.closing = true; // See "visibleTabs" getter in chrome://browser/content/tabbrowser.xml
		trgWindow.addEventListener("TabSelect", dontSelectHiddenTab, false);
	}
	else if(
		tab.getAttribute("pending") == "true" // Gecko >= 9.0
		|| tab.linkedBrowser.contentDocument.readyState == "uninitialized"
		// || tab.linkedBrowser.__SS_restoreState == 1
	)
		isPending = true;

	browser = tab.linkedBrowser;
	if(isPending || browser.webProgress.isLoadingDocument) {
		browser.addEventListener("load", processAddonsTab, true);
		if(isPending) {
			if(parseFloat(Services.appinfo.platformVersion) >= 41) {
				// Workaround to correctly restore pending tab
				// See https://github.com/Infocatcher/Custom_Buttons/issues/39
				let selTab = gBrowser.selectedTab;
				gBrowser.selectedTab = tab;
				gBrowser.selectedTab = selTab;
			}
			else {
				browser.reload();
			}
		}
	}
	else {
		processAddonsTab();
	}
}
else {
	progressIcon.restore();
	btn.tooltipText = tip;
	delete btn._cb_disabled;
	Services.prompt.alert(window, btn.label, "Error: Can't find supported window!");
	return;
}

function processAddonsTab(e, again) {
	var doc;
	if(e && e instanceof Components.interfaces.nsIDOMWindow) {
		doc = e.document;
	}
	else if(e) {
		doc = e.target;
		if(doc.location != ADDONS_URL)
			return;
		browser.removeEventListener(e.type, processAddonsTab, true);
	}
	else {
		doc = browser.contentDocument;
	}

	progressIcon.loading();

	var origAttr = "_cb_checkForAddonsUpdates_origImage";
	if(!tab.hasAttribute(origAttr))
		tab.setAttribute(origAttr, tab.image);
	tab.image = image;

	var updEnabledPref = "extensions.update.enabled";
	var updEnabled = Services.prefs.getBoolPref(updEnabledPref);
	if(!updEnabled)
		Services.prefs.setBoolPref(updEnabledPref, true);

	var fu = $("cmd_findAllUpdates");
	if(!fu) { // Firefox 72+
		var win = doc.defaultView;
		var vb = doc.getElementById("html-view-browser");
		if(!vb) {
			win.setTimeout(processAddonsTab, 20, win);
			return;
		}
		if(!again) { // Strange errors happens
			// chrome://mozapps/content/extensions/aboutaddons.js
			// getTelemetryViewName() -> el.closest(...) is null
			win.setTimeout(processAddonsTab, 20, win, true);
			return;
		}
		var vbDoc = vb.contentDocument;
		fu = vbDoc.querySelector('[action="check-for-updates"]');
		var um = vbDoc.getElementById("updates-message");
	}

	var notFound = $("updates-noneFound") || {
		get hidden() { return um.getAttribute("state") != "none-found"; }
	};
	var updated = $("updates-installed") || {
		get hidden() { return um.getAttribute("state") != "installed"; }
	};
	// Avoid getting false results from the past update check (may not be required for "noneFound")
	if(um) { // Firefox 72+
		um.hidden = true;
		um.removeAttribute("state");
	}
	else {
		notFound.hidden = updated.hidden = true;
	}

	//fu.doCommand();
	fu.click();

	function localize(node, key, callback) {
		if(um) { // Firefox 72+
			doc.l10n.formatValue(key).then(function(s) {
				callback(s || key);
			}, Components.utils.reportError);
			return;
		}
		callback(node.getAttribute("value") || key);
	}

	var inProgress = $("updates-progress") || {
		get hidden() { return um.getAttribute("state") != "updating"; },
		set hidden(h) {}
	};
	localize(inProgress, "addon-updates-updating", function(s) {
		btn.tooltipText = s;
	});

	var waitTimer = setInterval(function() {
		if(!doc.defaultView || doc.defaultView.closed) {
			stopWait();
			notify("Tab with add-ons manager was closed!");
			return;
		}
		if(!inProgress.hidden)
			return;
		var autoUpdate = $("utils-autoUpdateDefault")
			|| vbDoc.querySelector('[action="set-update-automatically"]');
		var autoUpdateChecked = autoUpdate.getAttribute("checked") == "true"
			|| autoUpdate.checked;

		var found = $("updates-manualUpdatesFound-btn") || {
			get hidden() { return um.getAttribute("state") != "manual-updates-found"; }
		};
		if(
			autoUpdateChecked
				? notFound.hidden && updated.hidden
				: notFound.hidden && found.hidden
		) // Too early?
			return;

		stopWait();
		if(!tbTab)
			tab.closing = false;
		function removeTab() {
			if(!tab.collapsed)
				return;
			if(tbTab)
				tabmail.closeTab(tbTabInfo, true /*aNoUndo*/);
			else {
				gBrowser.removeTab(tab);
				(function forgetClosedTab(isSecondTry) {
					var ss = "nsISessionStore" in Components.interfaces
						? (
							Components.classes["@mozilla.org/browser/sessionstore;1"]
							|| Components.classes["@mozilla.org/suite/sessionstore;1"]
						).getService(Components.interfaces.nsISessionStore)
						: SessionStore; // Firefox 61+ https://bugzilla.mozilla.org/show_bug.cgi?id=1450559
					if(!("forgetClosedTab" in ss))
						return;
					var closedTabs = JSON.parse(ss.getClosedTabData(window));
					for(let i = 0, l = closedTabs.length; i < l; ++i) {
						let closedTab = closedTabs[i];
						let state = closedTab.state;
						if(state.entries[state.index - 1].url == ADDONS_URL) {
							ss.forgetClosedTab(window, i);
							return;
						}
					}
					if(!isSecondTry) // May be needed in SeaMonkey
						setTimeout(forgetClosedTab, 0, true);
				})();
			}
		}

		if(!updEnabled)
			Services.prefs.setBoolPref(updEnabledPref, false);

		if(!notFound.hidden) {
			removeTab();
			localize(notFound, "addon-updates-none-found", function(s) {
				notify(s);
			});
			return;
		}
		if(autoUpdateChecked) {
			removeTab();
			localize(updated, "addon-updates-installed", function(s) {
				notify(s);
			});
			return;
		}

		tab.collapsed = false;
		var cats = $("categories");
		var upds = $("category-availableUpdates");
		if(vb && cats.selectedItem == upds) // Only for Firefox 72+
			cats.selectedItem = $("category-extension"); // Trick to force update
		cats.selectedItem = upds;
		var tabWin = tab.ownerDocument.defaultView;
		if(tbTab)
			tabmail.switchToTab(tbTabInfo);
		else
			tabWin.gBrowser.selectedTab = tab;
		setTimeout(function() {
			tabWin.focus();
			doc.defaultView.focus();
			var al = $("addon-list") || vb;
			al.focus();
		}, 0);
	}, 50);
	function $(id) {
		return doc.getElementById(id);
	}
	function stopWait() {
		clearInterval(waitTimer);
		progressIcon.restore();
		btn.tooltipText = tip;
		if(tab.image == image)
			tab.image = tab.getAttribute(origAttr);
		tab.removeAttribute(origAttr);
		trgWindow.removeEventListener("TabSelect", dontSelectHiddenTab, false);
		setTimeout(function() {
			delete btn._cb_disabled;
		}, 500);
	}
	function notify(msg) {
		Components.classes["@mozilla.org/alerts-service;1"]
			.getService(Components.interfaces.nsIAlertsService)
			.showAlertNotification(
				Services.appinfo.name == "Firefox" && parseFloat(Services.appinfo.version) >= 57
					? "chrome://mozapps/skin/extensions/extensionGeneric.svg"
					: "chrome://mozapps/skin/extensions/extensionGeneric.png",
				btn.label,
				msg, false, "", null
			);
	}
}
function dontSelectHiddenTab(e) {
	// <tab /><tab collapsed="true" />
	// Close first tab: collapsed tab becomes selected
	var trgTab = e.originalTarget || e.target;
	if(trgTab != tab)
		return;

	if(/\n(?:BrowserOpenAddonsMgr|toEM)@chrome:\/\//.test(new Error().stack)) {
		// User open Add-ons Manager, show tab
		trgWindow.removeEventListener("TabSelect", dontSelectHiddenTab, false);
		setTimeout(function() { // Hidden tab can't be selected, so select it manually...
			tab.collapsed = tab.closing = false;
			gBrowser.selectedTab = tab;
		}, 0);
	}

	function done(t) {
		if(!t.hidden && !t.closing) {
			e.preventDefault();
			e.stopPropagation();
			return gBrowser.selectedTab = t;
		}
		return false;
	}
	for(var t = tab.nextSibling; t; t = t.nextSibling)
		if(done(t))
			return;
	for(var t = tab.previousSibling; t; t = t.previousSibling)
		if(done(t))
			return;
}
function ProgressIcon(btn) {
	if(!(btn instanceof XULElement)) {
		this.loading = this.restore = function() {};
		return;
	}
	var app = Services.appinfo.name;
	var pv = parseFloat(Services.appinfo.platformVersion);
	if(app == "SeaMonkey")
		this.imgConnecting = this.imgLoading = "chrome://communicator/skin/icons/loading.gif";
	else if(app == "Thunderbird") {
		this.imgConnecting = "chrome://messenger/skin/icons/connecting.png";
		this.imgLoading = "chrome://messenger/skin/icons/loading.png";
	}
	else {
		this.imgConnecting = app == "Firefox" && pv >= 58
			? "chrome://browser/skin/tabbrowser/tab-connecting.png"
			: "chrome://browser/skin/tabbrowser/connecting.png";
		this.imgLoading = app == "Firefox" && pv >= 48
			? "chrome://global/skin/icons/loading.png"
			: "chrome://browser/skin/tabbrowser/loading.png";
	}
	var useAnimation = app == "Firefox" && pv >= 32 && pv < 48;
	var btnIcon = btn.icon
		|| btn.ownerDocument.getAnonymousElementByAttribute(btn, "class", "toolbarbutton-icon");
	var origIcon = btnIcon.src;
	btnIcon.src = this.imgConnecting;
	if(useAnimation) {
		let cs = btnIcon.ownerDocument.defaultView.getComputedStyle(btnIcon, null);
		let s = btnIcon.style;
		s.margin = [cs.marginTop, cs.marginRight, cs.marginBottom, cs.marginLeft].join(" ");
		s.padding = [cs.paddingTop, cs.paddingRight, cs.paddingBottom, cs.paddingLeft].join(" ");
		s.width = cs.width;
		s.height = cs.height;
		s.boxShadow = "none";
		s.borderColor = s.background = "transparent";
		btnIcon.setAttribute("fadein", "true");
		btnIcon.setAttribute("busy", "true");
		btnIcon.classList.add("tab-throbber");
		btnIcon._restore = function() {
			delete btnIcon._restore;
			btnIcon.removeAttribute("busy");
			btnIcon.removeAttribute("progress");
			setTimeout(function() {
				btnIcon.classList.remove("tab-throbber");
				btnIcon.removeAttribute("style");
				btnIcon.removeAttribute("fadein");
			}, 0);
		};
	}
	this.loading = function() {
		btnIcon.src = this.imgLoading;
		if(useAnimation)
			btnIcon.setAttribute("progress", "true");
	};
	this.restore = function() {
		btnIcon.src = origIcon;
		if(useAnimation)
			btnIcon._restore();
	};
}
}).call(this);
//== Check for Addons Updates end
}              

this.tooltipText = "Переключатель джетпаков" 
                   + "\n\nУправление:\nЛКМ – открыть меню" 
                   + "\nПКМ – проверить обновления"
                   + "\nСКМ – открыть страницу дополнений"
                   + "\nShift+ПКМ – меню кнопки"
                   + "\n\nВ меню: \nЛКМ – включить/выключить дополнение"
                   + "\nShift+ЛКМ – включить/выключить дополнение без закрытия меню"   
                   + "\nСКМ – открыть страницу дополнения в управлении дополнениями"                    
                   + "\nПКМ – открыть настройки дополнения (если есть)";     
// Autoopen/close feature
var openDelay = 200;
var closeDelay = 350;

var _openTimer = 0;
var _closeTimer = 0;
this.onmouseover = function(e) {
	clearTimeout(_closeTimer);
	if(e.target == this && closeOtherMenus()) {
		this.open = true;
		return;
	}
	_openTimer = setTimeout(function() {
		self.open = true;
	}, openDelay);
};
this.onmouseout = function(e) {
	clearTimeout(_openTimer);
	_closeTimer = setTimeout(function() {
		if(!isContextOpened())
			self.open = false;
	}, closeDelay);
};
function closeOtherMenus() {
	return Array.prototype.some.call(
		self.parentNode.getElementsByTagName("*"),
		function(node) {
			if(
				node != self
				&& node.namespaceURI == xulns
				// See https://github.com/Infocatcher/Custom_Buttons/issues/28
				//&& node.boxObject
				//&& node.boxObject instanceof Components.interfaces.nsIMenuBoxObject
				&& "open" in node
				&& node.open
				&& node.getElementsByTagName("menupopup").length
			) {
				node.open = false;
				return true;
			}
			return false;
		}
	);
}
function isContextOpened() {
	return inBtn(document.popupNode);
}
function inBtn(node) {
	for(; node; node = node.parentNode)
		if(node == self)
			return true;
	return false;
}

Отредактировано egorsemenov06 (21-04-2020 23:59:23)

Отсутствует

 

№829521-04-2020 21:09:09

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

contextsearch
ucf_custom_script_win.load

скрытый текст

Выделить код

Код:

(this.contextsearch = {
            topic: "browser-search-engine-modified",
            hide: "browser.search.hiddenOneOffs",
            defaultImg: "chrome://browser/skin/search-engine-placeholder.png",
            searchSelect: null,
            popup: null,
            init(that) {
                var searchSelect = this.searchSelect = document.querySelector("#context-searchselect");
                if (!searchSelect)
                    return;
                var popup = this.popup = searchSelect.closest("menupopup");
                popup.addEventListener("popupshowing", this);
                that.unloadlisteners.push("contextsearch");
            },
            destructor() {
                this.popup.removeEventListener("popupshowing", this);
                if (this.popupshowing == this.handler) {
                    this.popup.removeEventListener("popuphidden", this);
                    Services.obs.removeObserver(this, this.topic);
                    Services.prefs.removeObserver(this.hide, this);
                }
            },
            handleEvent(e) {
                this[e.type](e);
            },
            popupshowing(e) {
                var popup = this.popup;
                var searchSelect = this.searchSelect;
                if (e.target != popup || searchSelect.hidden) return;

                var menu = document.createXULElement("menu");
                menu.className = "menu-iconic";
                var menupopup = document.createXULElement("menupopup");
                menu.append(menupopup);
                menu.ePopup = menupopup;
                searchSelect.collapsed = true;
                searchSelect.before(menu);
                menu.onclick = this.search.bind(this);
                this.handler = ev => {
                    if (ev.target != popup) return;
                    menu.hidden = searchSelect.hidden;
                };
                this.handlerRebuild = () => this.handler(e) || this.rebuild(menu);
                this.popuphidden = ev => {
                    if (ev.target != popup) return;
                    menu.hidden = true;
                };
                this.popup.addEventListener("popuphidden", this);
                this.rebuild(menu);
            },
            async rebuild(menu) {
                var de = Services.search.defaultEngine;
                de = de.wrappedJSObject || de;
                this.setAttrs(menu, de, `Искать в ${de.name} или в ...`);
                menu.ePopup.textContent = "";
                var pref = Services.prefs.getStringPref("browser.search.hiddenOneOffs");
                var hiddenList = pref ? pref.split(",") : [];
                var engines = await Services.search.getVisibleEngines();
                for(let engine of engines.filter(e => !hiddenList.includes(e.name))) {
                    if (engine == de) continue;
                    var menuitem = document.createXULElement("menuitem");
                    menuitem.className = "menuitem-iconic";
                    this.setAttrs(menuitem, engine);
                    menu.ePopup.append(menuitem);
                }
                this.popupshowing = this.handler;
                Services.obs.addObserver(this, this.topic, false);
                Services.prefs.addObserver(this.hide, this);
            },
            setAttrs(node, engine, label = engine.name) {
                node.engine = engine;
                node.setAttribute("label", label);
                node.setAttribute("image", engine.iconURI ? engine.iconURI.spec : this.defaultImg);
            },
            observe() {
                this.popupshowing = this.handlerRebuild;
                Services.obs.removeObserver(this, this.topic);
                Services.prefs.removeObserver(this.hide, this);
            },
            search(e) {
                var {engine} = e.target;
                if (!engine) return;
                var searchSelect = this.searchSelect;
                var submission = engine.getSubmission(
                    searchSelect.searchTerms, null, "contextmenu"
                );
                if (submission) {
                    let tab = gBrowser.addTab(submission.uri.spec, {
                        postData: submission.postData,
                        index: (gBrowser.selectedTab._tPos + 1),
                        triggeringPrincipal: searchSelect.principal
                    });
                    if (e.button == 0)
                        gBrowser.selectedTab = tab;
                }
                var popup = this.popup;
                e.button != 1 && popup.state == "open" && popup.hidePopup();
            }
        }).init(this);

Отредактировано Vitaliy V. (23-04-2021 13:23:04)

Отсутствует

 

№829621-04-2020 21:47:10

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06
вот пока эту пробуйте
остальное завтра может посмотрю

Спасибо Огромное!!!
Может тогда глянете кнопку Прокси

скрытый текст

Выделить код

Код:

data:image/x-icon;base64,AAABAAEAEREAAAEAIADwBAAAFgAAACgAAAARAAAAIgAAAAEAIAAAAAAAyAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQAAAAAIAAYOQAAWJ2kADh1fAAAEKAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAEBAQECAgICAgICAgICAgMBAQEAAAEEJBE4ULQ+fZ38ea/H/muhuv8gW3ztAxclewAAAAsAAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEBAAAAAAMLNlO7PH+n/3Sgu/281eP9zuHr/mWZuP4XXon/ABAeZwAAAAAAAAAAAQEBAQAAAAAZGBoTKScsLyYkKjErJSgnIC8/XgZQgP9BcZb8b5q3/oiux/+qx9r/a5Ow+zFtlv8PRWrGAAACAAEBAQMHBwcbAAAAD2BeYn769/3/4eDm/Onh5v+DnrX/A0t9/j1vlv+FqMH/lrfN/7rS4f9+pL3+M26X/xJYhu0DEiMdAAAAAAEBAQEAAAABBgUGEaSiprbPzNP239fb/4OcsP4aXYr/RHOZ/5Gwx//T5e//mrjO/3KYtv40apP/D0x77AUTIhwhHyMmeXV7mXt4fqJ3dHmce3d+n6eirODMx8r/o6q3/kN4nf92m7n/vtPj/9Hg7P/C1OL/eJq1+jtulv8bSnC7AAEGAF1aYH7//////f39/P//////////////////////////lbHC/3ilvf/K4Oz/2OXv/7nN3f6FqcP/VIiv/AseMT8AAAAAXFtef+LY5/+AT534fU2d+4VXovyKXaf+jGGp/5BlrP+GWKT/ZmGc/4Cduf+ivtD+k7HH/1t/neUTJjhFAAAAAAEBAQJfXmB/3tHl/14giPxcIYr/Zy+S/244mP9yPZv/cj6c/3M9nP9wNpf/YDSP/1k0ivu7tdP/YmNmiAAAAAAEBAQGAAAAAF9eYIDg1Ob/cDqV/HE9mv9/TaT/hler/4tdr/+NXrD/iFms/4JTqP9+SqP/cjqW+9zJ4/9ubW6JAAAAAAMDBAQAAAAAX15ggODU5v94RZz8e0mi/4pcrv+Vabf/nXO9/6J5wf+jfMH/oXq//513u/+NY6z718bh/2pqa4gAAAAABAMEBAAAAABfXWCA4NTm/4VWpfyPY7L/onvA/7GPzP+8ndT/waTY/8Cj1/+6nNL/tZfO/6F9uvvYx+L/ampriAAAAAAEAwQEAAAAAF9eYH/e0uX/n3u5/LKTzP/Bpdf/zrbh/9jC6f/bxuv/2cTp/9O+5P/Qu+H/uJ3L+9jI4f9qaWuHAAAAAAQDBAQAAAAAX15gf97S5P+gfbf5sZPH/LqdzfzCqNT8ybHZ/My12vzKs9n8xq/W/Mav1fywksL418fh/2tqbIkAAAAABAMEBAAAAABZVlt3+fX8/+DU5vzj1un/5tvt/+ne7//r4PH/6t7w/+fb7f/k2Ov/4dPn/9nM4Pv79v//ZGFnfwAAAAADAwQEAAAAABcVGRpZVlt6YF9hgWBgYoBhYWKAYmFigGJiY4BiYmOAYmFigGFhYoBgYGGAX15ggF1aX4AbGR0eAAAAAAEBAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=


скрытый текст

Выделить код

Код:

// Настройка функций кликов мыши для кнопки ...................
this.onmousedown = e => {

    if (e.button == 0) // длинный левый клик
        self.timer = setTimeout(() => {
            self.onmouseup = null;
            cbu.getPrefs("CB.Proxy.connectionsInTab")
                ? openConnectionsInTab() : openConnections();
        }, 500);

    this.onmouseup = e => { // левый клик
        if (e.button) return;
        clearTimeout(self.timer);

        switch(cbu.getPrefs("network.proxy.type")) {
            case 0:  var data = 1; break;
            case 1:  var data = 2; break;
            default: var data = 0; 
        }
        cbu.setPrefs("network.proxy.type", data);
    }
}
// правый клик
this.oncontextmenu = e => e.detail == 2 && !menuPopup.hidePopup()
    || e.ctrlKey || !!menuPopup.openPopup(this, "after_start");


// Подсказка для кнопки ...................
this.onmouseover = () => this.tooltipText =
    "Proxy \nЛ:  Переключить прокси \nДЛ: Открыть настройки прокси" +
    "\nП:  Mеню кнопки \nДП: CB меню \n\nТекущие настройки прокси: " +
    "\nIP: " + cbu.getPrefs("network.proxy.http") + "\nПорт: " +
    cbu.getPrefs("network.proxy.http_port");


// Создать меню для кнопки ...................
var array = [
    {label: "Добавление прокси в контекстом меню", value: 'CB.Proxy.inContextMenu'},
    {label: "Открывать настройки прокси как вкладку", value: 'CB.Proxy.connectionsInTab'},
    {label: "Переключать на режим 'Без прокси' при закрытии браузера ", value: 'CB.Proxy.reset'}
];

var menuPopup = document.getElementById('mainPopupSet').appendChild(document.createElementNS(xulns, "menupopup"));
array.forEach(m => {
    var mItem = document.createElementNS(xulns, "menuitem");
    mItem.setAttribute("label", m.label);
    mItem.setAttribute("type", "checkbox");
    mItem.setAttribute("checked", cbu.getPrefs(m.value));
    mItem.onclick = () => cbu.setPrefs(m.value, !cbu.getPrefs(m.value));  
    menuPopup.appendChild(mItem);
});
addDestructor(() => menuPopup.remove());


var listenClick = win => {
    var args = ["click", win.close.bind(win), true];
    var unload = () => gBrowser.removeEventListener(...args);
    gBrowser.addEventListener(...args);
    win.addEventListener("unload", unload, {once: true});
}
var version = parseInt(Services.appinfo.platformVersion);
var url = `chrome://browser/content/preferences/connection.x${version >= 72 ? "htm" : "u"}l`;

var fox73 = version >= 73, noop = () => {};
if (fox73) var grid = win => {
    var url = "data:text/css;charset=utf-8," + encodeURIComponent(`
        #proxy-grid, #dnsOverHttps-grid {
            display: grid;
            grid-template-columns: auto 1fr;
            align-items: center;
        }
        #proxy-grid > .thin {
            grid-column-end: 3;
            height: 20px;
        }
        #dnsOverHttps-grid.custom-container-hidden #networkCustomDnsOverHttpsInput,
        #dnsOverHttps-grid.custom-container-hidden #networkCustomDnsOverHttpsInputLabelContainer {
            display: none;
        }
    `);
    (grid = win => win.windowUtils.loadSheetUsingURIString(url, win.windowUtils.AUTHOR_SHEET))(win);
}
var winOpen = win => win.addEventListener("readystatechange", winReady, {once: true, capture: true});
var winReady = e => {
    var win = e.target.ownerGlobal, cw = win.isChromeWindow;
    if (cw || (win.location == url && !win.docShell.name)) winPatch(win, cw);
}
var winPatch = (win, cw) => {
    win.opener = {gSubDialog: {_dialogs: [{
        _frame: {get contentDocument() {
            cw && listenClick(win);
            delete this.contentDocument;
            return this.contentDocument = win.document;
        }},
        resizeVertically: cw ? () => win.sizeToContent() : noop
    }]}};
    fox73 && grid(win);
}
addEventListener("MozBeforeInitialXULLayout", winReady, false, gBrowser.tabpanels || 1);

for(var {contentWindow: win} of gBrowser.browsers)
    win && win.location == url && !win.opener && winPatch(win);


// Функция открывает настройки прокси в окне ...................  
function openConnections() {
    var win = [...Services.wm.getEnumerator(null)].find(w => w.location == url);
    win ? win.focus() : winOpen(openDialog(url, "Proxy", "centerscreen"));
}

// Функция открывает настройки прокси в вкладке ...................
function openConnectionsInTab() {
    var connections = gBrowser.getBrowserForTab(
        gBrowser.selectedTab = gBrowser.addTrustedTab(url)
    );

    // oбработчик ждет пока откроется прокси, удаляет себя и добавляет атрибут
    connections.addEventListener("pageshow",
        e => e.target.documentElement.setAttribute("type", "prefwindow")
    , {once: true});
}


// Установливать нужную иконку кнопки при старте баузера или при изменениях в 'about:config' ...................
var s = "network.proxy.type";
function toggleImage() {
    var {icon} = self;
    switch( cbu.getPrefs(s) ) {
        case 1: icon.src = 'data:image/x-icon;base64,AAABAAEAEREAAAEAIADwBAAAFgAAACgAAAARAAAAIgAAAAEAIAAAAAAAyAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQAAAAAIAA4GQAAnFmkAHQ5fAAQAKAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAEBAQECAgICAgICAgICAgMBAQEAAAQBJBFQOLQ+nX38ecev/mu6of8gfFvtAyUXewAAAAsAAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEBAAAAAAMLUza7PKd//3S7oP2849X9zuvh/mW4mf4XiV7/AB4QZwAAAAAAAAAAAQEBAQAAAAAZGhgTKSwnLyYqJDErKCUnID8vXgaAUP9BlnH8b7ea/ojHrv+q2sf/a7CT+zGWbf8PakXGAAIAAAEBAQMHBwcbAAAAD2BiXn76/ff/4ebg/Onm4f+DtZ7/A31L/j2Wb/+Fwaj/ls23/7rh0v9+vaT+M5du/xKGWO0DIxIdAAAAAAEBAQEAAAABBgYFEaSmorbP08z239vX/4OwnP4ail3/RJlz/5HHsP/T7+X/ms64/3K2mP40k2r/D3tM7AUiExwhIx8meXt1mXt+eKJ3eXSce353n6esouDMysf/o7eq/kOdeP92uZv/vuPT/9Hs4P/C4tT/eLWa+juWbv8bcEq7AAYBAF1gWn7//////f39/P//////////////////////////lcKx/3i9pf/K7OD/2O/l/7ndzf6Fw6n/VK+I/AsxHj8AAAAAXF5bf+Ln2P+AnU/4fZ1N+4WiV/yKp13+jKlh/5CsZf+GpFj/Zpxh/4C5nf+i0L7+k8ex/1udf+UTOCZFAAAAAAEBAQJfYF5/3uXR/16IIPxciiH/Z5Iv/26YOP9ymz3/cpw+/3OcPf9wlzb/YI80/1mKNPu707X/YmZjiAAAAAAEBAQGAAAAAF9gXoDg5tT/cJU6/HGaPf9/pE3/hqtX/4uvXf+NsF7/iKxZ/4KoU/9+o0r/cpY6+9zjyf9ubm2JAAAAAAMEAwQAAAAAX2BegODm1P94nEX8e6JJ/4quXP+Vt2n/nb1z/6LBef+jwXz/ob96/527d/+NrGP71+HG/2praogAAAAABAQDBAAAAABfYF2A4ObU/4WlVvyPsmP/osB7/7HMj/+81J3/wdik/8DXo/+60pz/tc6X/6G6ffvY4sf/amtqiAAAAAAEBAMEAAAAAF9gXn/e5dL/n7l7/LLMk//B16X/zuG2/9jpwv/b68b/2enE/9Pkvv/Q4bv/uMud+9jhyP9qa2mHAAAAAAQEAwQAAAAAX2Bef97k0v+gt335sceT/LrNnfzC1Kj8ydmx/MzatfzK2bP8xtav/MbVr/ywwpL41+HH/2tsaokAAAAABAQDBAAAAABZW1Z3+fz1/+Dm1Pzj6db/5u3b/+nv3v/r8eD/6vDe/+ft2//k69j/4efT/9ngzPv7//b/ZGdhfwAAAAADBAMEAAAAABcZFRpZW1Z6YGFfgWBiYIBhYmGAYmJhgGJjYoBiY2KAYmJhgGFiYYBgYWCAX2BegF1fWoAbHRkeAAAAAAEBAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='; break;
        case 2: icon.src = 'data:image/x-icon;base64,AAABAAEAEREAAAEAIADwBAAAFgAAACgAAAARAAAAIgAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAQAAAAAIAAcHQAAYGGkAEBBfAAEBKAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAABAQEAAgICAAICAgACAgMBAQEAAAEBJAA6OrQAf3/8ALCw/gCiov8AXl7tABkZewAAAAsAAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEBAAAAAAMAOTm7AIOD/wCjo/0A1tb9AOHh/gCcnP4AY2P/ABISZwAAAAAAAAAAAAEBAQAAAAAAGBgTACgoLwAmJjEAJiYnADIyXgBWVv8Adnb8AJ2d/gCxsf8Aycn/AJeX+wBycv8ASkrGAAACAAABAQMABwcbAAAADwBfX34A+fn/AOHh/ADj4/8AoaH/AFJS/gB1df8Aq6v/ALm5/wDT0/8Ap6f+AHNz/wBeXu0AFRUdAAAAAAABAQEAAAABAAUFEQCjo7YAzs72ANnZ/wCfn/4AY2P/AHl5/wCzs/8A5ub/ALu7/wCcnP4AcHD/AFNT7AAVFRwAICAmAHd3mQB6eqIAdXWcAHl5nwClpeAAyMj/AK2t/gB9ff8An5//ANXV/wDh4f8A1tb/AJ6e+gB0dP8AUFC7AAEGAABcXH4A////AP39/AD///8A////AP///wD///8A////ALOz/wCnp/8A4eH/AObm/wDPz/4ArKz/AI2N/AAhIT8AAAAAAFxcfwDd3f8Aa2v4AGpq+wBycvwAeHj+AHt7/wB/f/8Ac3P/AHNz/wCiov8AwMD+ALS0/wCEhOUAKSlFAAAAAAABAQIAXl5/ANjY/wBGRvwARkb/AFJS/wBaWv8AX1//AF9f/wBfX/8AWVn/AFRU/wBRUfsAvr7/AGNjiAAAAAAABAQGAAAAAABeXoAA2tr/AFtb/ABeXv8AbGz/AHV1/wB6ev8Ae3v/AHd3/wBxcf8Aamr/AFtb+wDS0v8AbW2JAAAAAAADAwQAAAAAAF5egADa2v8AZGT8AGlp/wB5ef8AhYX/AI2N/wCTk/8AlJT/AJKS/wCPj/8AfX37AM/P/wBqaogAAAAAAAMDBAAAAAAAXl6AANra/wBycvwAf3//AJOT/wClpf8AsLD/ALa2/wC1tf8Ar6//AKqq/wCTk/sA0ND/AGpqiAAAAAAAAwMEAAAAAABeXn8A2dn/AJGR/ACnp/8At7f/AMXF/wDQ0P8A09P/ANHR/wDLy/8AyMj/AK2t+wDR0f8AaWmHAAAAAAADAwQAAAAAAF5efwDY2P8AkpL5AKWl/ACurvwAuLj8AL+//ADCwvwAwMD8AL29/AC8vPwAo6P4ANDQ/wBqaokAAAAAAAMDBAAAAAAAV1d3APf3/wDa2vwA3d3/AOHh/wDk5P8A5ub/AOTk/wDh4f8A39//ANra/wDT0/sA+fn/AGNjfwAAAAAAAwMEAAAAAAAWFhoAV1d6AF9fgQBgYIAAYWGAAGFhgABiYoAAYmKAAGFhgABhYYAAYGCAAF5egABbW4AAGhoeAAAAAAABAQEAAAAA/oOAQeEAgEH6AIBBoACAQQAAAEGAAABBAACAQQAAgEEAAQBBAAKAQQACgEEAAoBBAAKAQQACgEEAAoBBAAKAQQACgEE='; break;
        default: icon.src = self.image;
    }
}
toggleImage();
Services.prefs.addObserver(s, toggleImage, false);
addDestructor(() => Services.prefs.removeObserver(s, toggleImage));


// Переключать на режим 'Без прокси' при закрытии браузера если это разрешено в 'about:config' ...................
var toggleButton = {
    observe(s, t, data) {
        cbu.getPrefs("CB.Proxy.reset") && data == "shutdown" && cbu.setPrefs("network.proxy.type", 0);
    }
};
Services.obs.addObserver(toggleButton, "quit-application", false);


// Создаем меню для добавление прокси в контекстном меню выделенного текста на странице ...................
var contextMenu = document.getElementById("contentAreaContextMenu");
var menuitem = document.createElementNS(xulns,"menuitem");
menuitem.setAttribute("label", "Добавить прокси");
menuitem.setAttribute("class", "menuitem-iconic");
menuitem.setAttribute("image", self.image);
menuitem.onclick =()=> addNewProxy(menuitem);
contextMenu.appendChild(menuitem); // как последний пункт меню
addDestructor(() => menuitem.remove());
addEventListener("popupshowing", () => {
    menuitem.hidden = !cbu.getPrefs("CB.Proxy.inContextMenu") || !gContextMenu.isContentSelected; // !gContextMenu.isTextSelected;
}, false, contextMenu);


// добавление прокси ...................
function addNewProxy(menuitem) {
    var sel = gBrowser.contentDocument
        ? gBrowser.contentDocument.defaultView.getSelection().toString() // Pale Moon  
        : gContextMenu.selectionInfo.fullText; // Firefox

    sel = sel.replace(/^\s+|\s+$/g, ""); // удалить пробелы, слева и справа от строки
    sel = sel.replace(/\s+/g, ":");      // заменить пробелы внутри строки

    // если только порт ...
    if (sel.length < 6 && isFinite(sel)) { 
        var lab = 'порт';
        cbu.setPrefs("network.proxy.http_port", +sel);                    
    }

    // если только адрес ...
    if (sel.length > 5 && !/:/.test(sel) && sel.split(".").length == 4) {
        var lab = 'адрес';
        cbu.setPrefs("network.proxy.http", convertFromUnicode("UTF-8", sel));  
    }

    // если адрес и порт ...    
    if (sel.length > 5 && /:/.test(sel) && sel.split(":").length == 2 && sel.split(".").length == 4) {
        var lab = 'адрес и порт';
        var arr = sel.split(":"), IP = arr[0], port = arr[1];
        cbu.setPrefs("network.proxy.http_port", +port);
        cbu.setPrefs("network.proxy.http", convertFromUnicode("UTF-8", IP));
    }

    // всплывающая подсказка рядом с выделенным текстом ...
    var mainPopupSet = document.getElementById('mainPopupSet');
    var tooltip = mainPopupSet.appendChild(document.createElementNS(xulns,"tooltip"));
    tooltip.style.cssText = "color: red !important; font-weight: bold !important; font-size: 14px !important; -moz-box-orient: horizontal; text-align: center;";

    var image = tooltip.appendChild(document.createElementNS(xulns, "image"));
    image.setAttribute("src", self.image);

    var label = tooltip.appendChild(document.createElementNS(xulns, "label"));
    label.setAttribute("value", "Установлен " + lab + " прокси: " + sel);

    tooltip.openPopup(menuitem.parentNode, "before_start");
    setTimeout(() => mainPopupSet.removeChild(tooltip), 3000);
};


// Конвертировать текст в юникод .............  
function convertFromUnicode(charset, str) {
    var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
    converter.charset = charset;
    str = converter.ConvertFromUnicode(str);
    return str + converter.Finish();
}

Отсутствует

 

№829721-04-2020 23:51:56

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06
эти коды не подходят для user_chrome_files
слишком много переделывать придется, так что я пас.
Но кнопка прокси есть у меня в расширении add_toolbar_buttons

Отсутствует

 

№829822-04-2020 00:08:40

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06
эти коды не подходят для user_chrome_files
слишком много переделывать придется, так что я пас.
Но кнопка прокси есть у меня в расширении add_toolbar_buttons

В ней функционала меньше

а эти тоже не подходят

скрытый текст

Выделить код

Код:

data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA


скрытый текст

Выделить код

Код:

(async obj => {
    Services.search.isInitialized || await Services.search.init();
    obj.observe();
    this.type = "menu";
    obj.popup = this.appendChild(document.createXULElement("menupopup"));
    addEventListener("popupshowing", obj, false, obj.popup);


    // https://github.com/Infocatcher/Custom_Buttons/blob/master/code_snippets/autoOpenCloseMenu.js
    // Automatically open menu on mouse over (and hide it on mouse out)

    //=======[ Start Autoopen/close feature ]=======
    var openDelay = 200;
    var closeDelay = 350;

    var _openTimer = 0;
    var _closeTimer = 0;
    this.onmouseover = function(e) {
        clearTimeout(_closeTimer);
        if(e.target == this && closeOtherMenus()) {
            this.open = true;
            return;
        }
        _openTimer = setTimeout(function() {
            self.open = true;
        }, openDelay);
    };
    this.onmouseout = function(e) {
        clearTimeout(_openTimer);
        _closeTimer = setTimeout(function() {
            if(!isContextOpened())
                self.open = false;
        }, closeDelay);
    };
    function closeOtherMenus() {
        return Array.prototype.some.call(
            self.parentNode.getElementsByTagName("*"),
            function(node) {
                if(
                    node != self
                    && node.namespaceURI == xulns
                    // See https://github.com/Infocatcher/Custom_Buttons/issues/28
                    //&& node.boxObject
                    //&& node.boxObject instanceof Components.interfaces.nsIMenuBoxObject
                    && "open" in node
                    && node.open
                    && node.getElementsByTagName("menupopup").length
                ) {
                    node.open = false;
                    return true;
                }
                return false;
            }
        );
    }
    function isContextOpened() {
        return inBtn(document.popupNode);
    }
    function inBtn(node) {
        for(; node; node = node.parentNode)
            if(node == self)
                return true;
        return false;
    }
    //=======[ End Autoopen/close feature ]=======

    var topic = "browser-search-engine-modified";
    Services.obs.addObserver(obj, topic, false);
    addDestructor(() => Services.obs.removeObserver(obj, topic));
    if (!obj.excludeHiddenOneOffs) return;
    var obs = () => obj.upd = true;
    Services.prefs.addObserver(obj.pref, obs);
    addDestructor(() => Services.prefs.removeObserver(obj.pref, obs));
})({
    excludeHiddenOneOffs: false,

    handleEvent() {
        var {popup} = this;
        popup.setAttribute("context", "");
        popup.setAttribute("position", "after_start");
        popup.setAttribute("oncommand", "Services.search.defaultEngine = event.target.engine");
        (this.handleEvent = () => this.upd && this.rebuild())();
    },
    async rebuild() {
        this.popup.textContent = "";
        var df = document.createDocumentFragment();
        var de = Services.search.defaultEngine.wrappedJSObject, jsde = this.json(de);
        if (this.excludeHiddenOneOffs)
            var ex = Services.prefs.getStringPref(this.pref, "").split(",");
        var check = true;
        for(var engine of await Services.search.getVisibleEngines()) {
            if (check && engine.name == de.name && this.json(engine) == jsde) {
                check = false; continue;
            }
            if (this.excludeHiddenOneOffs && ex.includes(engine.name)) continue;
            var menuitem = df.appendChild(document.createXULElement("menuitem"));
            menuitem.engine = engine;
            menuitem.label = engine.name;
            menuitem.image = this.img(engine);
            menuitem.className = "menuitem-iconic";
        }
        this.upd = this.popup.append(df);
    },
    observe() {
        var engine = Services.search.defaultEngine;
        (self.icon || document.getAnonymousElementByAttribute(
            self, "class", "toolbarbutton-icon"
        )).src = this.img(engine);
        self.tooltipText = engine.name;
        this.upd = true;
    },
    pref: "browser.search.hiddenOneOffs",
    json: e => JSON.stringify(e.toJSON()),
    img: e => e.iconURI ? e.iconURI.spec : "chrome://browser/skin/search-engine-placeholder.png"
});


скрытый текст

Выделить код

Код:

data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAACAAAAA0AAAARAAAAFAAAABQAAAASAAAADgAAAAkAAAAEAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAANAAAAGQAAACUAAAAwCj9NTBh3iXENV2hdAB4mQgAAADIAAAAoAAAAHAAAAA8AAAAEAAAAAAAAAAEAAAALAAAAGwAAACsAAAA6Ax4kUy6iucI6wdj5NbrS7zGqwM0Wd4uLAygySwAAAC4AAAAeAAAADgAAAAIAAAABAAAACQAAABgAAAAnAAAANhh6jYUzwdf4IsLa/yTF3P83xtz/OcHY+SKowskVc4hfABEZHgAAAAwAAAACAAAAAAAAAAEAAAAHAAAAEQAwNyUsssq+IMXd/x3F3/8vzeX/J8Lb/xe91/83yt//O73U5iinw2YAbZEHAAAAAAAAAAAAAAAAAAAAAAAAAAESobopL8Tc4xzM5f8m0uz/Jcnj/xvB2/8cw9v/M8Tb/1DJ3vA2t9OMAKq/DAAAAAAAAAAAAAAAAAAAAAAAAAAAIrLRQzbR6PQw2vL/Ndjx/yTN5/8Yxd7/J8Tb/0rI3dw4uNRaAKnGCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAB1DRtvr3dF1O36TeL4/0Pd9P8n1Oz/Icfe/jzD288ptNE+AH//AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMhFEFDaXwMmDC/17A5P9O4vj/NNXr/TLC2sEercsyAP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACcxBoaocisI26//Ss8xP88SMv/NnzF9jG31pkXqdAhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAosUWG6jIoEfI4f1jweT/PmjD+Q4XmK4AKIYTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD1+PEBVwpqoWfrH+PbHR4UzE3ccHXJskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD9/BCF2qXIefrv3GXiy8AxtoU8QpscuAJnMBQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB5uoDMvhLniHYLB/yR8srcAW5EOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAndahVQIi0+jaGuPYhdKlaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEmSaHCV1qI0ndad1Em2RDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAMmAIABJgAAACYAAAAmAIABJgDgASYA8AMmAOAHJgDgDyYAwD8mAMB/JgDA/yYAgP8mAIP/JgCH/yYAh/8mAA==


скрытый текст

Выделить код

Код:

(this.preventClearThumbs || (g => {
    var key = "onClearHistory", obs = g.PageThumbsHistoryObserver, func = obs[key];
    return this.preventClearThumbs = () => obs[key] = () => obs[key] = func;
})(Cu.import("resource://gre/modules/PageThumbs.jsm", {})))(); 

PlacesUtils.history.clear();
 var closedTabCount = SessionStore.getClosedTabCount(window);
 while(closedTabCount--) SessionStore.forgetClosedTab(window, 0);
      
       alertsService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
       alertsService.showAlertNotification("chrome://global/skin/icons/cpd_OK.png", "PrivateData", "История Очищена" );
       setTimeout(()=> alertsService.closeAlert(), 2000);

Отредактировано egorsemenov06 (22-04-2020 00:13:04)

Отсутствует

 

№829922-04-2020 00:37:01

Vitaliy V.
Участник
 
Группа: Members
Зарегистрирован: 19-09-2014
Сообщений: 2027
UA: Firefox 76.0

Re: Настройка внешнего вида Firefox в userChrome.css

egorsemenov06
Да эта тоже не слишком удобная, дело в том что
чтобы создать кнопку в user_chrome_files нужно использовать
метод CustomizableUI.createWidget в custom_script.js а это уже другая область,
этот код там просто так не заработает.
Если есть код где не нужно создавать кнопки,
ну или можно с кнопкой но где поменьше кода.

Вторую кнопку сделаю

Отсутствует

 

№830022-04-2020 00:53:45

egorsemenov06
Участник
 
Группа: Members
Зарегистрирован: 12-06-2018
Сообщений: 258
UA: Firefox 75.0

Re: Настройка внешнего вида Firefox в userChrome.css

Vitaliy V. пишет

egorsemenov06

Вторую кнопку сделаю

а эти пойдут Savefrom

скрытый текст

Выделить код

Код:

data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAr0lEQVR42s2RQQqDMBBFB9zXg7tt13bdS3iGFkSk0DMIQaGrMb/NlEmaiS666OJhiP8/hgkxMwn9CZ/3+XE5sCaXAfQ/gv5IPJ6rTQEyyMaCtn6F9grmrmZ0fjhB4Nps70BnvgQaS5DysWI0IS0LOiOTRDuwiinmDvZIdDm7g5IkLZtLzEly5eIrDEoyGOWiYPLcW2IwGZlI4JyjZZnp6c+38ESjLwMOd/iHDLLSWwH9gcgAuHHDqgAAAABJRU5ErkJggg==

скрытый текст

Выделить код

Код:

/*Initialization Code*/

// Настройка функций кликов мыши для кнопки ..............
this._handleClick = () => gBrowser.selectedTab = gBrowser.addTrustedTab(
    "http://savefrom.net/?url=" + escape(gBrowser.currentURI.spec)
);

// Получаем из вкладки Справка массив с доменами закачку из которые подерживает savefrom ..............
var hosts = this.Help.split("\n").filter(host => /\S/.test(host)).map(host => host.trim());

// Если хост сайта совпадает с массивом меняем иконку и подсказку ..............
var img = this.icon || document.getAnonymousNodes(this)[0];
var listener = e => {
    if (!e.target.selected) return;   
    var uri = gBrowser.currentURI;
    if (
        uri.scheme.startsWith("http") &&
        hosts.includes(uri.host.replace(/^www\./, ""))
    )
        self.tooltipText = "Есть видео для загрузки",     
        img.src = "data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAdUlEQVR42mP4//8/Awznb9H8j8xGxtjUgDDD4DEAm0JcBiDzMRQTawBMjDouoFogohuGzQB0jFUxsRhrGJCiGWsYkKIZaxiQohlnIBKrmXqxgA1/QDLkAw41KAZ8/vyZ4du3rww/kRILsu0gGiQHUgNSC9MHAAnDrTG2r95iAAAAAElFTkSuQmCC";
    else
        self.tooltipText = "Нет видео для загрузки",
        img.src = this.image;
}
addEventListener("TabAttrModified", listener, false, gBrowser.tabContainer);
listener({target: gBrowser.selectedTab});


RAM
скрытый текст

Выделить код

Код:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAACXBIWXMAAAsSAAALEgHS3X78AAAAJUlEQVQImWP8////TwYGBjYGBPjF+P////8MaIAJXQCv4Ed0QQBCWgnsd3Yz5gAAAABJRU5ErkJggg==


скрытый текст

Выделить код

Код:

/*Initialization Code*/

// ====================================================================================
// Memory Monitor ................................
// https://forum.mozilla-russia.org/viewtopic.php?id=52237
// ====================================================================================
var idbut=this.id;
var urlbar = document.getElementById("page-action-buttons");
var button = document.getElementById(idbut);
urlbar.insertBefore(button, urlbar.lastChild);

var style = custombutton.buttonGetHelp(self).replace(/id/g, _id);
var uri = makeURI('data:text/css,'+ encodeURIComponent(style));
var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
sss.loadAndRegisterSheet(uri, 0);     
 
// Подсказка кнопки ................................
this.tooltipText = "П: Очистка Кеш";  

                  
// Настройка функций кликов мыши для кнопки ................................
this.onclick = function(e) {
     e.target.setAttribute("context", "event.stopPropagation()");      
     if ( e.button == 0) {
      
          // очистить кэш ....
          try {
              Services.cache.evictEntries(Ci.nsICache.STORE_IN_MEMORY);
              Services.cache.evictEntries(Ci.nsICache.STORE_ON_DISK);
              }
          catch(e) { Services.cache2.clear() }
    

          // Всплывающее сообщение ....
          var alertService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
          alertService.showAlertNotification('chrome://global/skin/icons/cpd_OK.png', 'СООБЩЕНИЕ', 'Очистил кеш');
          setTimeout(function() { alertService.closeAlert() }, 2000);   
          }
};
         
// Показывать потребление памяти на текущей кнопке
(function () { 
   self.timer = setInterval(function() {
   var memory = getMemory();
   self.label = getMemory()
     
       if ( memory < 520 ) return;
 }, 200 );
 
// Получить всю занимаемую оперативную память в MB ....
   function getMemory() {           
      var reporterManager = Cc["@mozilla.org/memory-reporter-manager;1"].getService(Ci.nsIMemoryReporterManager);
      try {
          var e = reporterManager.enumerateReporters();
          while ( e.hasMoreElements() ) {
                  var mr = e.getNext().QueryInterface(Ci.nsIMemoryReporter);
                  self[mr.path] = mr;
                  }
          var memory = self["resident"].amount;
          }
      catch(e) { var memory = reporterManager.resident; } // FF26 - Nightly
     
      return ( Math.round( memory/1048576 ) );
   };     

// Стиль добавляет текст на кнопку ....
   var uri = makeURI('data:text/css,'+ encodeURIComponent('\
   %button% .toolbarbutton-icon {\
     display: none !important;\
   }\
   %button% .toolbarbutton-text {\
     display: -moz-box !important;\
   }\
   %button% {\
     -moz-box-orient: horizontal !important;\
   }\
   '.replace(/%button%/g, "#" + _id) ));
   const sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
   sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
   
// Удалять счётчик памяти и другие изменения ....
  addDestructor(function() {
      try { window.clearTimeout( self.timer ) } catch(e) {};
   });
})();


Открыть в другом брузере
скрытый текст

Выделить код

Код:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAACXBIWXMAAAsSAAALEgHS3X78AAAEgUlEQVQ4jU2TW2yTZQCG3+/7v/79266HraN1G8cNVoERNhk42BBmghiQBF3IMJnghYcbxUPEREiYF0bgihBREyNRQ4wENCwkBjlsyIA5WclWOe3ANrq2W1u6reu5/f//+7xQI8/tmzx5bx4yMjKCgYEByLIMAYBTirymEUYpbIrimkslzKXOpwLrV3NNceTAhZERNVfFC1mnNifGjO6i8NB4grCOjg7s378foBSVNju+3b6D+NUC/d43oGeK7dXLFlfu9BhKr244XObntvuvkPDURszNGiSjkhKTaYAtPO7tT15iQggAAASHVZJIs8sFlDqx69l1O4Lh+EeVddXPidrZN2XeZcDvswrGqnhBXXXowK2rRxtXGF0vy4XWzvOhG4wQ8o+IUCIAkYcoYrr+pXlqdo+nwQXR6BUk1WP13qhE5pRZX2cDMRRpn9U/LK870/egrfkZ66WCqir/P4IQakGHIad/LUaDbWrLIs2w+TbFyB16J75PDNg3I9V8XbKdO4GaEiffXWpqmZ8tN01Oq20ffLwuTv+1SOACvM7S+hcLtknbyzR56z0p2T9If3nYjmtTtSQV9BF51RqML1yOlP8hiQUfqU00va33RGD3a69fEZRQQgDoJmaAceu8t+/tWwxsDxK9o5OcOduICxE3ykvSSBUvhR66D1W/heyyGDG/GJLwxgSWb4q8NXh3xkgBEABQi6WqxvUr6neVzwHXbtJQO8dgQEWJG4gqZfDM3URZVzuml21DyRYdhk0JwutzWN0CT2OttJY6HApxWICG5uqad6qZVRry8s8j88j9YAJJi4JR5kZvnxfV1w+id8EupBreA1m5CNSVJZxRYTYT04JyuoTt2bNGb939KQjXthUNX8DJqAU/Oi1IbnFiY0UFgots2Onx4BQ/iC6sRX0sCclTBuR8EIQAnEAiRGYyM4MZ3PV06trz/Y81nM4UwZXOYLhlIbKPFdTHIzjh8+G3+FLkC1nU1uiQ2AMUIAlGOclnZR6OIcI4MTGiJzfoY4OlP0zbM1mJmx2KhHSxBe6KOKKBIdyOOFBpIHjaY8SOJV8AGT9ALKCEIDDBogODWj8DrBpJB+smxjPdV84Xeua3LjjCZUmzaBbmjffAVNGPl6pWIJGVYNW9KFE7IJgZah6abDYbfvq18HNsjocoVD8QuOWyrWzqyT1Qj4b/CPsU2cSy+bSWt+YwU4ihO9mJ7vhlNCndsBiMSGaYbmFWg7fX4D92OnEEACjJ+iEyYatTqI9qXBJ8x3yt492ROxQyQ07S5QLTcxmb/oKS0TebVS2dtOpWUSz19Rn9be2xV2eTPEQJqHTow70Q8T/X0vjjpuaaeRdnptPR/gujPekEXyOZjfN1JhOH0Ogn9gi15BTyKKDQ785lR949Htk7EVV7KAHlApyok5ehDn9lZdnJ9yU9l6Ys03X4ZMR/4GzCqtjleqnCXu1xs+IGU56MRrX43bHcWGimcJsQhADkhYAOAESdvIj80Dcw5vMYGQ7i4KlBdN4tIJEVIBD4L+knoRSAAPgT49/cEBl9hsIr+QAAAABJRU5ErkJggg==


скрытый текст

Выделить код

Код:

this.onclick =e=> {
   e.button == 0 && menu.openPopup(this, "after_start");
   e.button == 1 && getAppPath();    
};


var menu = self.appendChild(document.createElementNS(xulns,"menupopup"));
addEventListener("popuphidden", ()=> setTimeout(()=> addToHelp(), 50), true, menu);

         
function setItemsToMenu(newPath = false) {
   menu.textContent = "";
   
   menu.onclick =(e, el = e.target, but = e.button)=> {
      e.preventDefault();
      e.stopPropagation();
      
      but == 0 && el.path && openWith(el.path);
      but == 1 && addToSeparator(e);
      !e.ctrlKey && but == 2 && removeNode(e);
      e.ctrlKey && but == 2 && changeMenuitemLabel(e);
   }

   var array = newPath ? (getHelp() + ',' + newPath).split(',') : getHelp();       
   array.forEach(path=> {
      if (path == "") return;
      if (path == "separator") { menu.appendChild(document.createElementNS(xulns,"menuseparator")); return };
      
      var mItem = menu.appendChild(document.createElementNS(xulns,"menuitem"));
      mItem.value = path;
      mItem.path = path.split(">").shift();
      
      var name = path.split("\\").pop().replace(".exe", ""),
          name = (/>/.test(name)) ? name.split(">").pop() : name,
          name = name[0].toUpperCase() + name.slice(1);
      
      mItem.setAttribute("label", name);
      mItem.setAttribute("tooltiptext", mItem.path);
      mItem.setAttribute("class", "menuitem-iconic");
      mItem.setAttribute("image", "moz-icon://file://" + mItem.path);
      mItem.onwheel =e=> moveNode(e);
   })
};
setItemsToMenu();


function moveNode(e, el = e.target) {
   menu.insertBefore(el, e.deltaY > 0 ? el.nextSibling.nextSibling : (el.previousSibling || el));
};


function addToSeparator(e, el = e.target) {
   menu.insertBefore(document.createElementNS(xulns,"menuseparator"), el.nextSibling);
};


function removeNode(e, el = e.target) {
   el.remove();
};


function changeMenuitemLabel(e, el = e.target) {
   menu.hidePopup();
   el.setAttribute("context", "event.stopPropagation()");
   
   var label = custombuttons.promptBox('', 'Ведите другое название пункта')[1];
   if (label != '') {
       el.value = el.value.split(">").shift() + ">" + label;
       el.setAttribute('label', label);
       }
};

 
function getAppPath() {
   var fp = window.makeFilePicker();
   fp.init(window, "Открыть файл", fp.modeOpen);
   fp.appendFilters(fp.filterApps);
   fp.init(window, "Укажите путь к программе", fp.modeOpen);
   fp.open(result => result == fp.returnOK && setItemsToMenu(fp.file.path));
};


function getHelp() { 
   return self.getAttribute('Help').split('\n').filter((path)=> /\S/.test(path)); 
};


function addToHelp() {
   var paths = [...menu.children].map((el)=> el.value || "separator").join("\n");

   var link = custombuttons.makeButtonLink("update", _id);
   var params = custombuttons.cbService.getButtonParameters(link).wrappedJSObject;
   params.help = paths;
   custombuttons.cbService.installButton(params.wrappedJSObject = params);
};


function openWith(path) {
   var uri = gBrowser.currentURI.spec;
   var uri = /.рф/.test(uri) ? Services.io.newURI(uri, null, null).asciiSpec : uri;  

   var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
   file.initWithPath(path);
   !file.exists() && custombuttons.alertSlide(self.label, "Файл не существует");
   var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
   process.init(file);
   process.run(false, [uri], 1);
};


this.tooltipText = "Л: Открыть меню с браузерамы \nС: Добавить в меню новый браузер\
                   \n\nФункции кликов мыши для меню:\
                   \n  Л: Открыть страницу\
                   \n  С: Добавить разделитель\
                   \n  П: Удалить пункт меню или разделитель\
                   \n  Ctrl+П: Изменить название пункта меню\
                   \n  Колёсиком мыши можно передвигать пункты меню или разделители";
this.type = "menu";

// Autoopen/close feature
var openDelay = 200;
var closeDelay = 350;

var _openTimer = 0;
var _closeTimer = 0;
this.onmouseover = function(e) {
	clearTimeout(_closeTimer);
	if(e.target == this && closeOtherMenus()) {
		this.open = true;
		return;
	}
	_openTimer = setTimeout(function() {
		self.open = true;
	}, openDelay);
};
this.onmouseout = function(e) {
	clearTimeout(_openTimer);
	_closeTimer = setTimeout(function() {
		if(!isContextOpened())
			self.open = false;
	}, closeDelay);
};
function closeOtherMenus() {
	return Array.prototype.some.call(
		self.parentNode.getElementsByTagName("*"),
		function(node) {
			if(
				node != self
				&& node.namespaceURI == xulns
				// See https://github.com/Infocatcher/Custom_Buttons/issues/28
				//&& node.boxObject
				//&& node.boxObject instanceof Components.interfaces.nsIMenuBoxObject
				&& "open" in node
				&& node.open
				&& node.getElementsByTagName("menupopup").length
			) {
				node.open = false;
				return true;
			}
			return false;
		}
	);
}
function isContextOpened() {
	return inBtn(document.popupNode);
}
function inBtn(node) {
	for(; node; node = node.parentNode)
		if(node == self)
			return true;
	return false;
}

Отредактировано egorsemenov06 (22-04-2020 06:54:48)

Отсутствует

 

Board footer

Powered by PunBB
Modified by Mozilla Russia
Copyright © 2004–2020 Mozilla Russia GitHub mark
Язык отображения форума: [Русский] [English]