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

Mozilla Россия — свежие версии программ Mozilla, а также масса полезной информации по каждому продукту.

№1257612-05-2018 11:53:51

Duche
Участник
 
Группа: Members
Зарегистрирован: 07-02-2016
Сообщений: 208
UA: Firefox 38.0

Re: Custom Buttons

bunda1 пишет

А там не надо ничего править.

Я предварительно так и сделал. Думал что есть единая специализированная команда. Спасибо за помощь.

Отсутствует

 

№1257714-05-2018 21:45:15

Dumby
Участник
 
Группа: Members
Зарегистрирован: 12-08-2012
Сообщений: 2242
UA: Firefox 52.0

Re: Custom Buttons

Новая версия конфигурационного кода.
Причина: на бете 61 не работали WebExtensions «системы paxmod».

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

Выделить код

Код:

//
try {(code => {
    var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
    var jsval, evl = true, re = e => Cu.reportError(e), imp = name => {try {
        return Cu.import(`resource://gre/modules/addons/${name}.jsm`, {});
    } catch(ex) {}}
    if ((jsval = imp("AddonSettings"))) {
        jsval.AddonSettings = {ADDON_SIGNING: false, REQUIRE_SIGNING: false, ALLOW_LEGACY_EXTENSIONS: true};
        try {evl = jsval.eval("this") === jsval;} catch(ex) {evl = false;}
    }
    lockPref("extensions.allow-non-mpc-extensions", true);
    var jsvals = ["XPIProvider", "XPIInstall"].map(imp).filter(i => i);

    if (evl) return jsvals.forEach(jsval => {try {jsval.eval(code);} catch(ex) {re(ex);}});

    var sl = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
    Cu.importGlobalProperties(["URL", "Blob"]); var url = URL.createObjectURL(new Blob([(code)]));
    jsvals.forEach(jsval => {try {sl.loadSubScript(url, jsval);} catch(ex) {re(ex);}});

})(String.raw`((vzss, pckg) => {
    var trueDesc = {enumerable: true, value: true};
    typeof Extension == "function" && Object.defineProperty(Extension.prototype, "experimentsAllowed", trueDesc);
    "AddonInternal" in this && Object.defineProperty(AddonInternal.prototype, "providesUpdatesSecurely", trueDesc);
    this.isDisabledLegacy = () => false;
    if ("XPIDatabase" in this) this.XPIDatabase.isDisabledLegacy = () => false;
    try {SIGNED_TYPES.clear();} catch(ex) {};

    if (!vzss && !pckg) return;

    var re = /\x06\x03U\x04\x03\x14[\s\S](\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)0\x82\x02"0\r\x06\t/i;
    var getUUID = () => {
        var gen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
        return (getUUID = () => gen.generateUUID().toString())();
    }
    var getIdFromString = str => {
        var match = str && str.match(re);
        return match ? match[1] : getUUID();
    }
    var getState = arg => ({
        signedState: AddonManager.SIGNEDSTATE_NOT_REQUIRED,
        cert: typeof arg == "object" ? arg : {commonName: arg}
    });
    var checkAddon = addon => {
        if (addon.id || addon._installLocation.name == KEY_APP_TEMPORARY)
            return getState(null);
    }
    var getRoot = () =>
        !AppConstants.MOZ_REQUIRE_SIGNING && Services.prefs.getBoolPref(PREF_XPI_SIGNATURES_DEV_ROOT, false)
            ? Ci.nsIX509CertDB.AddonsStageRoot : Ci.nsIX509CertDB.AddonsPublicRoot;

    if (vzss) {
        var getURI = file => {
            var jsval = Cu.import("resource://gre/modules/addons/XPIProvider.jsm", {});
            return (getURI = file => jsval.getURIForResourceInFile(file, "META-INF/mozilla.rsa"))(file);
        }
        var getIdFromFile = file => {
            var str, is = {close() {}}, sis = {close() {}};
            try {
                is = Services.io.newChannelFromURIWithLoadInfo(getURI(file), null).open();
                sis = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
                sis.init(is);
                str = sis.readBytes(sis.available());
            } catch(ex) {}
            sis.close(); is.close();
            return getIdFromString(str);
        }
        this.verifyZipSignedState = function verifyZipSignedState(aFile, aAddon) {
            var res = checkAddon(aAddon);
            return res ? Promise.resolve(res) : new Promise(resolve => {
                var callback = {openSignedAppFileFinished(rv, zipReader, cert) {
                    zipReader && zipReader.close();
                    resolve(getState(cert || getIdFromFile(aFile)));
                }};
                gCertDB.openSignedAppFileAsync(getRoot(), aFile, callback.wrappedJSObject = callback);
            });
        }
    }

    if (pckg) Package.prototype.verifySignedState = function verifySignedState(addon) {
        var res = checkAddon(addon);
        return res ? Promise.resolve(res) : new Promise(resolve =>
            this.verifySignedStateForRoot(addon, getRoot()).then(({cert}) => {
                if (cert)
                    resolve(getState(cert));
                else
                    this.readBinary("META-INF", "mozilla.rsa").then(
                        buffer => resolve(getState(
                            getIdFromString(String.fromCharCode(...new Uint8Array(buffer)))
                        )),
                        () => resolve(getState(getUUID()))
                    );
            }, Cu.reportError)
        );
    }
})(
    "verifyZipSignedState" in this, typeof Package == "function"
);`)} catch(err) {Components.utils.reportError(err);}

Отсутствует

 

№1257815-05-2018 00:25:11

sonyas75
Участник
 
Группа: Members
Откуда: Ставрополь
Зарегистрирован: 22-03-2011
Сообщений: 557
UA: Firefox 57.0

Re: Custom Buttons

этот код уже никогда работать не будет?

Выделить код

Код:

((lst, trg) => trg && addEventListener("mouseover", lst, false, trg))({
    id: 0, tab: null,
    handleEvent({target: tab}) {
        if (tab.matches("tab:not([selected])") && this.tab != tab) clearTimeout(this.id),
            this.id = setTimeout(this.onTimeout, 450, this.tab = tab, tab.boxObject.screenX);
    },
    get onTimeout() {
        delete this.onTimeout; return this.onTimeout = (tab, x) => {
            if (tab.matches(":hover") && Math.abs(x - tab.boxObject.screenX) < 50)
                gBrowser.selectedTab = tab;
            this.tab = null;
        }
    }
}, gBrowser.tabContainer.mTabstrip);

Отредактировано sonyas75 (15-05-2018 00:26:04)

Отсутствует

 

№1257915-05-2018 04:18:04

Dumby
Участник
 
Группа: Members
Зарегистрирован: 12-08-2012
Сообщений: 2242
UA: Firefox 52.0

Re: Custom Buttons

sonyas75
Замени gBrowser.tabContainer.mTabstrip на что-нибудь другое,
например на gBrowser.tabs[0].boxObject.parentBox

Отсутствует

 

№1258015-05-2018 09:09:29

sonyas75
Участник
 
Группа: Members
Откуда: Ставрополь
Зарегистрирован: 22-03-2011
Сообщений: 557
UA: Firefox 57.0

Re: Custom Buttons

Dumby
да вы волшебник! :D я тут в̶е̶ш̶а̶л̶с̶я̶  пил с горя четыре дня из-за этого, теперь пойду напьюсь с радости. шутка. на самом деле я к этой фичи привык настолько, что менял остальные 99% удобств ФФ на ЦентБраузер, когда с каким-то переходом у лисы отваливался СВ.

Отсутствует

 

№1258115-05-2018 09:38:37

Coroner
Участник
 
Группа: Members
Зарегистрирован: 29-10-2012
Сообщений: 4001
UA: Firefox 60.0

Re: Custom Buttons

sonyas75 пишет

да вы волшебник!

Присоединяюсь к мнению :)

sonyas75 пишет

на самом деле я к этой фичи привык

А что за фича хоть? Может и мне надо? :angel: Интерес разожгли,понимаешь...

Отсутствует

 

№1258215-05-2018 09:57:58

sonyas75
Участник
 
Группа: Members
Откуда: Ставрополь
Зарегистрирован: 22-03-2011
Сообщений: 557
UA: Firefox 57.0

Re: Custom Buttons

активировать вкладку наведением курсора. просто я в равной мере пользую мышей и устройства разной степени уродливости под названием тачпады. привык - кинул курсор вверх до упора на нужную вкладку - оба-на, она активная, но не сразу, а с задержкой в целых 450 мс, да :D вотЪ

Отредактировано sonyas75 (15-05-2018 09:59:14)

Отсутствует

 

№1258322-05-2018 22:04:07

func4ptch4
Участник
 
Группа: Members
Зарегистрирован: 03-05-2018
Сообщений: 220
UA: unknown 0.0

Re: Custom Buttons

Можно починить этот код? Заранее спасибо Dumby :).

Выделить код

Код:

//Bookmarks add-underline
({style: `@namespace url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul);
.tabbrowser-tab[inbookmarks] .tab-text.tab-label {text-decoration: underline !important;}   //background-color: yellow !important;
`.trim(),addProcessingInstruction: function(add) {if (add) {this.pi = document.createProcessingInstruction("xml-stylesheet",
`type="text/css" href="data:text/css,${encodeURIComponent(this.style)}"`);document.insertBefore(this.pi, document.firstChild);
} else this.pi.remove();},init: function() {this.addProcessingInstruction(true);this.setAttributeForAllTabs(true);
gBrowser.addTabsProgressListener(this);PlacesUtils.addLazyBookmarkObserver(this);addDestructor(this.destroy, this);},
destroy: function() {this.addProcessingInstruction(false);this.setAttributeForAllTabs(false);gBrowser.removeTabsProgressListener(this);
PlacesUtils.removeLazyBookmarkObserver(this);},isBookmarked: uri => Boolean(PlacesUtils.getBookmarksForURI(uri).length),
onItemAdded: function(id, parent, ind, type, uri) this.onItem(type, uri),onItemRemoved: function(id, parent, ind, type, uri) this.onItem(type, uri),
onItemChanged: function(id, property, isAnno, value, lm, type) property == "uri" && this.onItem(type),onItem: function(type, uri) {type == Ci.nsINavBookmarksService.TYPE_BOOKMARK
&& this.setAttributeForAllTabs(true, uri);},onLocationChange: function(browser, wp, req, uri) {var tab = gBrowser.getTabForBrowser(browser);
this.setAttributeForTab(tab, this.isBookmarked(uri));},setAttributeForAllTabs: function(set, uri) {for(var tab of gBrowser.tabs) {var curr = tab.linkedBrowser.currentURI;
if (uri && !uri.equals(curr)) continue;var state = set && this.isBookmarked(curr);this.setAttributeForTab(tab, state);}},setAttributeForTab: function(tab, set) {
set ? tab.setAttribute("inbookmarks", true) : tab.removeAttribute("inbookmarks");}}).init();

Отсутствует

 

№1258423-05-2018 07:54:23

Dumby
Участник
 
Группа: Members
Зарегистрирован: 12-08-2012
Сообщений: 2242
UA: Firefox 52.0

Re: Custom Buttons

func4ptch4
:/

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

Выделить код

Код:

({
    style: `
        tab.tabbrowser-tab[inbookmarks] .tab-text.tab-label {
            text-decoration: underline !important;
            /*background-color: yellow !important;*/
        }
    `,
    addProcessingInstruction(add) {
        if (add) this.pi = document.insertBefore(
            document.createProcessingInstruction(
                "xml-stylesheet",
                `type="text/css" href="data:text/css,${
                    encodeURIComponent(this.style.trim())
                }"`
            ), document.firstChild);
        else
            this.pi.remove();
    }, 
    init() {
        this.addProcessingInstruction(true);
        this.setAttributeForAllTabs(true);
        gBrowser.addTabsProgressListener(this);
        PlacesUtils.bookmarks.addObserver(this);
        addDestructor(this.destroy, this);
    },
    destroy() {
        this.addProcessingInstruction(false);
        this.setAttributeForAllTabs(false);
        gBrowser.removeTabsProgressListener(this);
        PlacesUtils.bookmarks.removeObserver(this);
    },
    async isBookmarked(url) {
        try {return Boolean(await PlacesUtils.bookmarks.fetch({url}));}
        catch(ex) {return false;}
    },
    onItemAdded(id, parent, ind, type, uri) {this.onItem(type, uri)},
    onItemRemoved(id, parent, ind, type, uri) {this.onItem(type, uri)},
    onItemChanged(id, property, isAnno, value, lm, type) {
        property == "uri" && this.onItem(type);
    },
    onItem(type, uri) {
        type == Ci.nsINavBookmarksService.TYPE_BOOKMARK
        && this.setAttributeForAllTabs(true, uri);
    },
    async onLocationChange(browser, wp, req, uri) {
        var tab = gBrowser.getTabForBrowser(browser);
        this.setAttributeForTab(tab, await this.isBookmarked(uri.spec));
    },
    async setAttributeForAllTabs(set, uri) {
        for (var tab of [...gBrowser.tabs]) {
            var curr = tab.linkedBrowser.currentURI;
            if (uri && !uri.equals(curr))
                continue;
            var state = set && await this.isBookmarked(curr.spec);
            this.setAttributeForTab(tab, state);
        }
    },
    setAttributeForTab(tab, set) {
        set ? tab.setAttribute("inbookmarks", true) : tab.removeAttribute("inbookmarks");
    }
}).init();

Отредактировано Dumby (23-05-2018 07:55:22)

Отсутствует

 

№1258523-05-2018 08:57:55

drage2
Забанен
 
Группа: Members
Откуда: Донецк
Зарегистрирован: 23-11-2017
Сообщений: 392
UA: Firefox 60.0

Re: Custom Buttons

Dumby пишет

Можно починить этот код? Заранее спасибо Dumby

Что это за код?

Отсутствует

 

№1258623-05-2018 10:22:56

Garalf
Участник
 
Группа: Members
Зарегистрирован: 19-09-2017
Сообщений: 315
UA: Firefox 60.0

Re: Custom Buttons

Dumby
А этот код слабо поправить?)

Выделить код

Код:

// Запустить QTranslate и жмакнуть(программно) дважды CTRL(код Dumby)
// - стандартн. комбин. для захвата текста из окна в QTranslate.
// интервал можно увеличить или уменьшить, зависит от железа
 setTimeout(function() dblCtrlSend(), 1000);

 quickTranslate();

 // ----------------------------------- =  QuickTranslate  = ----------------------------------------------
   function quickTranslate() {
//  скопировать выделенный текст в буфер. 
//       gClipboard.write(document.commandDispatcher.focusedWindow.getSelection().toString());
     var profile = Services.dirsvc.get('ProfD', Ci.nsIFile);
     profile.initWithPath(profile.path + "\\_QTranslate\\QTranslate.exe");
      var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
      var arg = [];
   process.init(profile);
   process.run(false, [arg], 1);
//   setTimeout(function() window.content.focus(), 500);
   };


function dblCtrlSend() {

// See https://gist.github.com/Noitidart/0de3be2442a0295eb386
// vk codes: https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx

// Double Ctrl [Ctrl-Down, Ctrl-Up, Ctrl-Down, Ctrl-Up]
var data = [[0x11, false], [0x11, true], [0x11, false], [0x11, true]];

// Ctrl+Q [Ctrl-Down, Q-Down, Q-Up, Ctrl-Up]
//var data = [[0x11, false], [0x51, false], [0x51, true], [0x11, true]];

var {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm", {});
var KEYBDINPUT = ctypes.StructType("tagKEYBDINPUT", [
    {wVk: ctypes.unsigned_short},
    {wScan: ctypes.unsigned_short},
    {dwFlags: ctypes.unsigned_long},
    {time: ctypes.unsigned_long},
    {dwExtraInfo: ctypes.voidptr_t.size == 8 ? ctypes.uint64_t : ctypes.unsigned_long},
    {padding0: ctypes.uint8_t.array(8)}
]);
var INPUT = ctypes.StructType("tagINPUT", [{type: ctypes.unsigned_long}, {ki: KEYBDINPUT}]);
var pInputs = INPUT.array()(data.map(([vkCode, keyup]) => 
    INPUT(1, KEYBDINPUT(vkCode, 0, keyup ? 2 : 0, 0, 0, ctypes.uint8_t.array(8)()))
));
var user32 = ctypes.open("user32"); try {
    var SendInput = user32.declare("SendInput", ctypes.winapi_abi, ctypes.unsigned_int, ctypes.unsigned_int, INPUT.ptr, ctypes.int);
    SendInput(pInputs.length, pInputs, INPUT.size);
 } finally {
    user32.close();
 }
};

В FF57 еще работал...

Отредактировано Garalf (23-05-2018 10:24:43)

Отсутствует

 

№1258723-05-2018 10:43:40

drage2
Забанен
 
Группа: Members
Откуда: Донецк
Зарегистрирован: 23-11-2017
Сообщений: 392
UA: Firefox 57.0

Re: Custom Buttons

А, нельзя просто Preview , без переключения ?

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

Выделить код

Код:

/*Initialization Code*/
((lst, trg) => trg && addEventListener("mouseover", lst, false, trg))({
    id: 0, tab: null,
    handleEvent({target: tab}) {
        if (tab.matches("tab:not([selected])") && this.tab != tab) clearTimeout(this.id),
            this.id = setTimeout(this.onTimeout, 450, this.tab = tab, tab.boxObject.screenX);
    },
    get onTimeout() {
        delete this.onTimeout; return this.onTimeout = (tab, x) => {
            if (tab.matches(":hover") && Math.abs(x - tab.boxObject.screenX) < 50)
                gBrowser.selectedTab = tab;
            this.tab = null;
        }
    }
}, gBrowser.tabs[0].boxObject.parentBox);

Отсутствует

 

№1258823-05-2018 11:42:06

unter_officer
Участник
 
Группа: Members
Откуда: Санкт-Петербург
Зарегистрирован: 27-03-2011
Сообщений: 595
UA: Firefox 47.0

Re: Custom Buttons

Исправьте пожалуйста кнопку под [firefox] 60+

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

Выделить код

Код:

// Показывать количество открытых табов в адресной строке
(()=> {  
   // Создать в адресной строке счётчик вкладок ....
   var tabCounter = document.createElement("statusbarpanel");
   tabCounter.setAttribute("id", "tabCounter");
   tabCounter.setAttribute("context", "event.stopPropagation()");
   tabCounter.setAttribute("tooltiptext", "Количество открытых вкладок"); 
   var urlbarIcons = document.getElementById("urlbar-icons") || document.getElementById("page-action-buttons"); // FF57
   urlbarIcons.insertBefore(tabCounter, urlbarIcons.lastChild);
   addDestructor(()=> tabCounter.remove() );


   // Css стиль для счётчика ....
   var uri = makeURI('data:text/css,'+ encodeURIComponent('\
      #tabCounter { -moz-appearance: none !important; font-family: Segoe UI !important; font-size: 12px !important; min-width: 32px !important; min-height: 24px !important; max-height: 24px !important; text-align: center !important; color: #000000 !important; background-color: #DBEAF9 !important; border-top: #DBEAF9 2px solid !important; border-right: 0 !important; border-bottom: #DBEAF9 2px solid !important; border-left: #B5C2D0 1px solid !important; margin-right: 0px !important; }\
   '));
   var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
   sss.loadAndRegisterSheet(uri, 0);
   addDestructor(()=> sss.unregisterSheet(uri, 0) ); 
   
   
   // Считать и показывать количество вкладок ....
   function count() {
     try { window.clearTimeout(count.timeout) } catch(e) {};
     count.timeout = window.setTimeout(()=> {
        tabCounter.label = gBrowser.tabs.length;
     }, 350);
   };
   count();


   // Отслеживать открытие, закрытие вкладок ....
   var tabs = gBrowser.tabContainer;
   addEventListener("TabOpen", count, false, tabs);
   addEventListener("TabClose", count, false, tabs);
})();


«The Truth Is Out There»

Отсутствует

 

№1258923-05-2018 12:19:37

func4ptch4
Участник
 
Группа: Members
Зарегистрирован: 03-05-2018
Сообщений: 220
UA: Firefox 60.0

Re: Custom Buttons

Вообщето и у меня много кодов для исправления, но я понимаю что нельзя наглеть ;)....
Будет время может и починит, и вообще спасибо ему за его дело...

Garalf
Насчет Autocopy Обсуждение кнопок CB | Форум Mozilla Россия

Отредактировано func4ptch4 (23-05-2018 13:36:46)

Отсутствует

 

№1259023-05-2018 17:33:11

func4ptch4
Участник
 
Группа: Members
Зарегистрирован: 03-05-2018
Сообщений: 220
UA: Firefox 60.0

Re: Custom Buttons

У меня вопрос по этой кнопке, если его и реально восстанивить, то сколько примерно он проработает?
Имеет ли смысл его переделывать или легче удалить? если там не знаю в 62 версий он сломается.
Вот сам код, п.с он не пашет.

Reload user{Chrome, Content}.css

Выделить код

Код:

(obj => {
    this.onclick = obj.click.bind(obj);
    this.oncontextmenu = obj.contextmenu.bind(obj);
    this.tooltipText = "L: Reload userChrome.css\nM: CB Menu\nR: Reload userContent.css";
})({
    click(e) {
        if (e.button == 1) return gShowPopup(self);
        if (e.button || !this.chromeSheet) return;
        this.reload(this.chromeSheet);
        this.restyle(0);
    },
    async contextmenu(e) {
        if (e.ctrlKey || e.shiftKey || e.detail != 1 || !this.contentSheetURL) return;
        e.preventDefault();

        var count = Services.ppmm.childCount, one = count == 1;
        var data = await this.reloadTab("about:config", one ? false : {});
        if (one) this.reloadTab();
        else if (data) {
            var url = "data:," + encodeURIComponent(
                self.Help + this.contentSheetURL + '", ' + JSON.stringify(data) + ");"
            );
            var types = ["web", "file", "extension"];
            for(var ind = 0; ind < count; ind++) {
                var child = Services.ppmm.getChildAt(ind);
                types.includes(child.remoteType) && child.loadProcessScript(url, false);
            }
        }
        this.restyle(250);
    },
    reload(sheet, obj) {
        var style = Cu.readURI(Services.io.newURI(sheet.href));
        this.inIDOMUtils.parseStyleSheet(sheet, style);
        if (obj) obj[sheet.href] = style;
        for(var ind = 0, len = sheet.cssRules.length; ind < len; ind++) {
            var rule = sheet.cssRules.item(ind);

            rule.type == rule.IMPORT_RULE
            && rule.styleSheet.href.startsWith("file:///")
            && this.reload(rule.styleSheet, obj);
        }
        return obj;
    },
    reloadTab(url, obj) {
        var tab = gBrowser.addTab(url);
        return new Promise(resolve => {
            var result, stop, destroy = () => {
                if (!stop) resolve(result), gBrowser.removeTab(tab), stop = true;
            }
            setTimeout(destroy, 500);
            try {
                gBrowser.hideTab(tab);
                tab.linkedBrowser.addEventListener("DOMContentLoaded", e => {
                    var sheet = this.getSheet(e.target, this.contentSheetURL);
                    if (sheet) result = this.reload(sheet, obj);
                    destroy();
                }, {once: true});
            } catch(ex) {
                destroy();
            }
        });
    },
    getSheet(doc, href) {
        var sheets = this.inIDOMUtils.getAllStyleSheets(doc);
        return sheets.find(sheet => sheet.href == href);
    },
    get contentSheetURL() {
        var file = Services.dirsvc.get("UChrm", Ci.nsIFile);
        file.append("userContent.css");
        if (!file.exists()) return null;
        delete this.contentSheetURL;
        return this.contentSheetURL = Services.io.newFileURI(file).spec;
    },
    get inIDOMUtils() {
        delete this.inIDOMUtils;
        return this.inIDOMUtils = Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils);
    },
    get restyle() {
        var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
        var uri = Services.io.newURI("data:text/css,:root{}"), type = sss.USER_SHEET;
        delete this.restyle; return this.restyle = delay => setTimeout(() => {
            sss.loadAndRegisterSheet(uri, type);
            sss.unregisterSheet(uri, type);
        }, delay);
    },
    get chromeSheet() {
        var file = Services.dirsvc.get("UChrm", Ci.nsIFile);
        file.append("userChrome.css");
        if (!file.exists()) return null;

        var href = Services.io.newFileURI(file).spec;
        var sheet = this.getSheet(document, href);
        if (!sheet) return null;

        delete this.chromeSheet; return this.chromeSheet = sheet;
    }
});


CB

Выделить код

Код:

custombutton://%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%0D%0A%3Ccustombutton%20xmlns%3Acb%3D%22http%3A//xsms.nm.ru/custombuttons/%22%3E%0A%20%20%3Cname%3EReload%20user%7BChrome%2C%20Content%7D.css%3C/name%3E%0A%20%20%3Cimage%3E%3C%21%5BCDATA%5Bdata%3Aimage/png%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAIpwAACKcBMsYCAwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAMwSURBVEiJ5dbNb5RVFMfxz3mmrYgYE0IN4IaKb4n4UqOwMCYu2JCoQVDiwoUrQ4j0xao7ExITQxRoodEFK1cmRkSE8AeYYKpEFF0YY4SiUSMRQW0sLe0818U8nekwHe3U7vhtnnNOzj3f89znPvderjVFK8npaSWrPSjpElahQzhvyrF4y++t1GqbF7DHOvQLj6Ozrt2EDutYRHAasMK0vXgWWZO0SX/7DlJf6Skp3UWcFeVRV4zG235tCZx6rDPtKLqqAN4XPhROm3DJEiG3LA6aKkZ14jUSKaOd1Gsco6Qz8vRiDDvTFJz63S13AjdVAg7JvBxDzs2RfrE2MP9ijolZijvJXo/h8pmmb5z6LZf7qICWJQNxwP5mM1OnzNdy03V1U0oi2x77y+/Wp16t3CDWgvDKvKGIQZepfO+iWBIpKG9s7HGW0k7dKgsJjsSQffOF1or4srAuS04U9jOp14amYGGgiF2Re6llaEWnMSbPNyl5DtNFQzvnBKdd2oRNhXt4ZvW1rCwfkbInY9jHMeiscBiEJ9Lz2mfSaovgovXC8sI7siAoYsgnMy8JkmPYhhtdbwOV6a9NdVhT69qphYIblPl0FuO2WrimVVVrcu7dZkFqd75q525uBCelqj0tXzRwvSYbwWZ1doOVi4Yad0vVDj81gjPfV+2y9YsGLnlgFrj6p9TA405irPAemwmn/raNqc/D/wO9uXj+bMhXDeDihDledLYt9VmTektb5flxebYgcOpx+yzw0aic3vXgSqY9hdUuOUx6T+WWcX/LUELYh3ZMyqq1G8FxwCl8ULjdVFd6d6tgPQbMfLIwHIPONgVXWs1OFm3Mjt6Rdlg2X2bq0yfsLtzP/OHVq3PqzuPUm/Vj9xz9ZDrcg5F/Bb6gS8mbkq1F6EdlW+IdE03Baae1pEeJb1SuO0vrMvPsPvKRArDaChf8qWRal/BQccBsxnXFiBFTtjS7czW93qYdVurQJZW6SLeK+DaGyofSLh0uGUNHk6F/SfZI3ojh2k41b3DThnrdS+1/nAnjcxzR5mDsdeG/6szrXl2nJX4w4RFJJ3LhF7lzMey3lmtdU/oHaoj4Y/PDRWgAAAAASUVORK5CYII%3D%5D%5D%3E%3C/image%3E%0A%20%20%3Cmode%3E0%3C/mode%3E%0A%20%20%3Cinitcode%3E%3C%21%5BCDATA%5B%28obj%20%3D%3E%20%7B%0A%09this.onclick%20%3D%20obj.click.bind%28obj%29%3B%0A%09this.oncontextmenu%20%3D%20obj.contextmenu.bind%28obj%29%3B%0A%09this.tooltipText%20%3D%20%22L%3A%20Reload%20userChrome.css%5CnM%3A%20CB%20Menu%5CnR%3A%20Reload%20userContent.css%22%3B%0A%7D%29%28%7B%0A%09click%28e%29%20%7B%0A%09%09if%20%28e.button%20%3D%3D%201%29%20return%20gShowPopup%28self%29%3B%0A%09%09if%20%28e.button%20%7C%7C%20%21this.chromeSheet%29%20return%3B%0A%09%09this.reload%28this.chromeSheet%29%3B%0A%09%09this.restyle%280%29%3B%0A%09%7D%2C%0A%09async%20contextmenu%28e%29%20%7B%0A%09%09if%20%28e.ctrlKey%20%7C%7C%20e.shiftKey%20%7C%7C%20e.detail%20%21%3D%201%20%7C%7C%20%21this.contentSheetURL%29%20return%3B%0A%09%09e.preventDefault%28%29%3B%0A%0A%09%09var%20count%20%3D%20Services.ppmm.childCount%2C%20one%20%3D%20count%20%3D%3D%201%3B%0A%09%09var%20data%20%3D%20await%20this.reloadTab%28%22about%3Aconfig%22%2C%20one%20%3F%20false%20%3A%20%7B%7D%29%3B%0A%09%09if%20%28one%29%20this.reloadTab%28%29%3B%0A%09%09else%20if%20%28data%29%20%7B%0A%09%09%09var%20url%20%3D%20%22data%3A%2C%22%20+%20encodeURIComponent%28%0A%09%09%09%09self.Help%20+%20this.contentSheetURL%20+%20%27%22%2C%20%27%20+%20JSON.stringify%28data%29%20+%20%22%29%3B%22%0A%09%09%09%29%3B%0A%09%09%09var%20types%20%3D%20%5B%22web%22%2C%20%22file%22%2C%20%22extension%22%5D%3B%0A%09%09%09for%28var%20ind%20%3D%200%3B%20ind%20%3C%20count%3B%20ind++%29%20%7B%0A%09%09%09%09var%20child%20%3D%20Services.ppmm.getChildAt%28ind%29%3B%0A%09%09%09%09types.includes%28child.remoteType%29%20%26%26%20child.loadProcessScript%28url%2C%20false%29%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%09this.restyle%28250%29%3B%0A%09%7D%2C%0A%09reload%28sheet%2C%20obj%29%20%7B%0A%09%09var%20style%20%3D%20Cu.readURI%28Services.io.newURI%28sheet.href%29%29%3B%0A%09%09this.inIDOMUtils.parseStyleSheet%28sheet%2C%20style%29%3B%0A%09%09if%20%28obj%29%20obj%5Bsheet.href%5D%20%3D%20style%3B%0A%09%09for%28var%20ind%20%3D%200%2C%20len%20%3D%20sheet.cssRules.length%3B%20ind%20%3C%20len%3B%20ind++%29%20%7B%0A%09%09%09var%20rule%20%3D%20sheet.cssRules.item%28ind%29%3B%0A%0A%09%09%09rule.type%20%3D%3D%20rule.IMPORT_RULE%0A%09%09%09%26%26%20rule.styleSheet.href.startsWith%28%22file%3A///%22%29%0A%09%09%09%26%26%20this.reload%28rule.styleSheet%2C%20obj%29%3B%0A%09%09%7D%0A%09%09return%20obj%3B%0A%09%7D%2C%0A%09reloadTab%28url%2C%20obj%29%20%7B%0A%09%09var%20tab%20%3D%20gBrowser.addTab%28url%29%3B%0A%09%09return%20new%20Promise%28resolve%20%3D%3E%20%7B%0A%09%09%09var%20result%2C%20stop%2C%20destroy%20%3D%20%28%29%20%3D%3E%20%7B%0A%09%09%09%09if%20%28%21stop%29%20resolve%28result%29%2C%20gBrowser.removeTab%28tab%29%2C%20stop%20%3D%20true%3B%0A%09%09%09%7D%0A%09%09%09setTimeout%28destroy%2C%20500%29%3B%0A%09%09%09try%20%7B%0A%09%09%09%09gBrowser.hideTab%28tab%29%3B%0A%09%09%09%09tab.linkedBrowser.addEventListener%28%22DOMContentLoaded%22%2C%20e%20%3D%3E%20%7B%0A%09%09%09%09%09var%20sheet%20%3D%20this.getSheet%28e.target%2C%20this.contentSheetURL%29%3B%0A%09%09%09%09%09if%20%28sheet%29%20result%20%3D%20this.reload%28sheet%2C%20obj%29%3B%0A%09%09%09%09%09destroy%28%29%3B%0A%09%09%09%09%7D%2C%20%7Bonce%3A%20true%7D%29%3B%0A%09%09%09%7D%20catch%28ex%29%20%7B%0A%09%09%09%09destroy%28%29%3B%0A%09%09%09%7D%0A%09%09%7D%29%3B%0A%09%7D%2C%0A%09getSheet%28doc%2C%20href%29%20%7B%0A%09%09var%20sheets%20%3D%20this.inIDOMUtils.getAllStyleSheets%28doc%29%3B%0A%09%09return%20sheets.find%28sheet%20%3D%3E%20sheet.href%20%3D%3D%20href%29%3B%0A%09%7D%2C%0A%09get%20contentSheetURL%28%29%20%7B%0A%09%09var%20file%20%3D%20Services.dirsvc.get%28%22UChrm%22%2C%20Ci.nsIFile%29%3B%0A%09%09file.append%28%22userContent.css%22%29%3B%0A%09%09if%20%28%21file.exists%28%29%29%20return%20null%3B%0A%09%09delete%20this.contentSheetURL%3B%0A%09%09return%20this.contentSheetURL%20%3D%20Services.io.newFileURI%28file%29.spec%3B%0A%09%7D%2C%0A%09get%20inIDOMUtils%28%29%20%7B%0A%09%09delete%20this.inIDOMUtils%3B%0A%09%09return%20this.inIDOMUtils%20%3D%20Cc%5B%22@mozilla.org/inspector/dom-utils%3B1%22%5D.getService%28Ci.inIDOMUtils%29%3B%0A%09%7D%2C%0A%09get%20restyle%28%29%20%7B%0A%09%09var%20sss%20%3D%20Cc%5B%22@mozilla.org/content/style-sheet-service%3B1%22%5D.getService%28Ci.nsIStyleSheetService%29%3B%0A%09%09var%20uri%20%3D%20Services.io.newURI%28%22data%3Atext/css%2C%3Aroot%7B%7D%22%29%2C%20type%20%3D%20sss.USER_SHEET%3B%0A%09%09delete%20this.restyle%3B%20return%20this.restyle%20%3D%20delay%20%3D%3E%20setTimeout%28%28%29%20%3D%3E%20%7B%0A%09%09%09sss.loadAndRegisterSheet%28uri%2C%20type%29%3B%0A%09%09%09sss.unregisterSheet%28uri%2C%20type%29%3B%0A%09%09%7D%2C%20delay%29%3B%0A%09%7D%2C%0A%09get%20chromeSheet%28%29%20%7B%0A%09%09var%20file%20%3D%20Services.dirsvc.get%28%22UChrm%22%2C%20Ci.nsIFile%29%3B%0A%09%09file.append%28%22userChrome.css%22%29%3B%0A%09%09if%20%28%21file.exists%28%29%29%20return%20null%3B%0A%0A%09%09var%20href%20%3D%20Services.io.newFileURI%28file%29.spec%3B%0A%09%09var%20sheet%20%3D%20this.getSheet%28document%2C%20href%29%3B%0A%09%09if%20%28%21sheet%29%20return%20null%3B%0A%0A%09%09delete%20this.chromeSheet%3B%20return%20this.chromeSheet%20%3D%20sheet%3B%0A%09%7D%0A%7D%29%3B%0A%5D%5D%3E%3C/initcode%3E%0A%20%20%3Ccode%3E%3C%21%5BCDATA%5B/*CODE*/%5D%5D%3E%3C/code%3E%0A%20%20%3Caccelkey%3E%3C%21%5BCDATA%5B%5D%5D%3E%3C/accelkey%3E%0A%20%20%3Chelp%3E%3C%21%5BCDATA%5B%28%28href%2C%20data%29%20%3D%3E%20%7B%0A%09var%20en%20%3D%20Services.ww.getWindowEnumerator%28null%29%3B%0A%09if%20%28%21en.hasMoreElements%28%29%29%20return%3B%0A%09var%20doc%20%3D%20en.getNext%28%29.document%3B%0A%0A%09var%20du%20%3D%20Components.classes%5B%22@mozilla.org/inspector/dom-utils%3B1%22%5D%0A%09%09.getService%28Components.interfaces.inIDOMUtils%29%3B%0A%09var%20reload%20%3D%20sheet%20%3D%3E%20%7B%0A%09%09var%20style%20%3D%20data%5Bsheet.href%5D%3B%20if%20%28%21style%29%20return%3B%0A%0A%09%09du.parseStyleSheet%28sheet%2C%20style%29%3B%0A%09%09for%28var%20ind%20%3D%200%2C%20len%20%3D%20sheet.cssRules.length%3B%20ind%20%3C%20len%3B%20ind++%29%20%7B%0A%09%09%09var%20rule%20%3D%20sheet.cssRules.item%28ind%29%3B%0A%0A%09%09%09rule.type%20%3D%3D%20rule.IMPORT_RULE%0A%09%09%09%26%26%20rule.styleSheet.href.startsWith%28%22file%3A///%22%29%0A%09%09%09%26%26%20reload%28rule.styleSheet%29%3B%0A%09%09%7D%0A%09%7D%0A%09var%20sheet%20%3D%20du.getAllStyleSheets%28doc%29.find%28sheet%20%3D%3E%20sheet.href%20%3D%3D%20href%29%3B%0A%09if%20%28sheet%29%20reload%28sheet%29%3B%0A%7D%29%28%22%5D%5D%3E%3C/help%3E%0A%20%20%3Cattributes/%3E%0A%3C/custombutton%3E

Отредактировано func4ptch4 (23-05-2018 17:37:49)

Отсутствует

 

№1259124-05-2018 10:21:42

drage2
Забанен
 
Группа: Members
Откуда: Донецк
Зарегистрирован: 23-11-2017
Сообщений: 392
UA: Firefox 57.0

Re: Custom Buttons

А, что СВ выше 60 приказал долго жить?

Отсутствует

 

№1259224-05-2018 10:55:51

Smitis
Участник
 
Группа: Members
Зарегистрирован: 29-01-2016
Сообщений: 10
UA: Firefox 60.0

Re: Custom Buttons

Подскажите, в последних версия Firefox content.document приказал долго жить? Например, content.document.getElementsByTagName('h1') всегда возвращает массив нулевой длины. Или есть какой-то другой способ получить доступ к содержимому страницы?

Отсутствует

 

№1259325-05-2018 21:51:36

Dumby
Участник
 
Группа: Members
Зарегистрирован: 12-08-2012
Сообщений: 2242
UA: Firefox 52.0

Re: Custom Buttons

Garalf пишет

А этот код слабо поправить?)

Править там особо нечего. dblCtrlSend() работает и на сегодняшней 62 (Win7).
quickTranslate() тоже работает, но что они делают совместно — не смог понять.
А setTimeout(function() dblCtrlSend(), 1000); — ну так «мне без сахара»,
раз работало, то просто замени на setTimeout(dblCtrlSend, 1000);

unter_officer пишет

Исправьте пожалуйста кнопку под [firefox] 60+

Там создаётся элемент "statusbarpanel", который
больше не представляет из себя ничего особенного.
Попробуй создавать что-нибудь другое, например, "label",
и тогда, соответственно, вместо tabCounter.label = ...
tabCounter.value = ...

func4ptch4 пишет

У меня вопрос по этой кнопке, если его и реально восстанивить, то сколько примерно он проработает?
Имеет ли смысл его переделывать или легче удалить? если там не знаю в 62 версий он сломается.

Не инсайдер, чтоб знать где что сколько проработает.
Не телепат, чтоб знать кому что легче, и что для кого имеет смысл.
А восстановить, ну можно попробовать.

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

Выделить код

Код:

custombutton://%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%0D%0A%3Ccustombutton%20xmlns%3Acb%3D%22http%3A//xsms.nm.ru/custombuttons/%22%3E%0A%20%20%3Cname%3EReload%20user%7BChrome%2C%20Content%7D.css%3C/name%3E%0A%20%20%3Cimage%3E%3C%21%5BCDATA%5Bdata%3Aimage/png%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAABHNCSVQICAgIfAh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0uGUNHk6F/SfZI3ojh2k41b3DThnrdS+1/nAnjcxzR5mDsdeG/6szrXl2nJX4w4RFJJ3LhF7lzMey3lmtdU/oHaoj4Y/PDRWgAAAAASUVORK5CYII%3D%5D%5D%3E%3C/image%3E%0A%20%20%3Cmode%3E0%3C/mode%3E%0A%20%20%3Cinitcode%3E%3C%21%5BCDATA%5B%28obj%20%3D%3E%20%7B%0A%09this.onclick%20%3D%20obj.click.bind%28obj%29%3B%0A%09this.oncontextmenu%20%3D%20obj.contextmenu.bind%28obj%29%3B%0A%09this.tooltipText%20%3D%20%22L%3A%20Reload%20userChrome.css%5CnM%3A%20CB%20Menu%5CnR%3A%20Reload%20userContent.css%22%3B%0A%7D%29%28%7B%0A%09async%20click%28e%29%20%7B%0A%09%09if%20%28e.button%20%3D%3D%201%29%20return%20gShowPopup%28self%29%3B%0A%09%09if%20%28e.button%20%7C%7C%20%21this.chromeSheet%29%20return%3B%0A%09%09await%20this.reload%28this.chromeSheet%29%3B%0A%09%09this.restyle%280%29%3B%0A%09%7D%2C%0A%09async%20contextmenu%28e%29%20%7B%0A%09%09if%20%28e.ctrlKey%20%7C%7C%20e.shiftKey%20%7C%7C%20e.detail%20%21%3D%201%20%7C%7C%20%21this.contentSheetURL%29%20return%3B%0A%09%09e.preventDefault%28%29%3B%0A%0A%09%09var%20count%20%3D%20Services.ppmm.childCount%2C%20one%20%3D%20count%20%3D%3D%201%3B%0A%09%09var%20data%20%3D%20await%20this.reloadTab%28%22chrome%3A//extensions/content/dummy.xul%22%2C%20one%20%3F%20false%20%3A%20%7B%7D%29%3B%0A%09%09if%20%28one%29%20this.reloadTab%28%29%3B%0A%09%09else%20if%20%28data%29%20%7B%0A%09%09%09var%20url%20%3D%20%22data%3A%2C%22%20+%20encodeURIComponent%28%0A%09%09%09%09self.Help%20+%20this.contentSheetURL%20+%20%27%22%2C%20%27%20+%20JSON.stringify%28data%29%20+%20%22%29%3B%22%0A%09%09%09%29%3B%0A%09%09%09var%20types%20%3D%20%5B%22web%22%2C%20%22file%22%2C%20%22extension%22%5D%3B%0A%09%09%09for%28var%20ind%20%3D%200%3B%20ind%20%3C%20count%3B%20ind++%29%20%7B%0A%09%09%09%09var%20child%20%3D%20Services.ppmm.getChildAt%28ind%29%3B%0A%09%09%09%09types.includes%28child.remoteType%29%20%26%26%20child.loadProcessScript%28url%2C%20false%29%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%09this.restyle%28250%29%3B%0A%09%7D%2C%0A%09async%20reload%28sheet%2C%20obj%29%20%7B%0A%09%09try%20%7Bvar%20style%20%3D%20await%20%28await%20fetch%28sheet.href%29%29.text%28%29%3B%7D%0A%09%09catch%20%28ex%29%20%7Breturn%20obj%3B%7D%0A%09%09InspectorUtils.parseStyleSheet%28sheet%2C%20style%29%3B%0A%09%09if%20%28obj%29%20obj%5Bsheet.href%5D%20%3D%20style%3B%0A%09%09for%28var%20ind%20%3D%200%2C%20len%20%3D%20sheet.cssRules.length%3B%20ind%20%3C%20len%3B%20ind++%29%20%7B%0A%09%09%09var%20rule%20%3D%20sheet.cssRules.item%28ind%29%3B%0A%0A%09%09%09rule.type%20%3D%3D%20rule.IMPORT_RULE%0A%09%09%09%26%26%20rule.styleSheet.href.startsWith%28%22file%3A///%22%29%0A%09%09%09%26%26%20await%20this.reload%28rule.styleSheet%2C%20obj%29%3B%0A%09%09%7D%0A%09%09return%20obj%3B%0A%09%7D%2C%0A%09reloadTab%28url%2C%20obj%29%20%7B%0A%09%09var%20tab%20%3D%20gBrowser.addTab%28url%2C%20%7BskipAnimation%3A%20true%7D%29%3B%0A%09%09tab.style.setProperty%28%22display%22%2C%20%22none%22%2C%20%22important%22%29%3B%0A%09%09return%20new%20Promise%28resolve%20%3D%3E%20%7B%0A%09%09%09var%20result%2C%20stop%2C%20destroy%20%3D%20%28%29%20%3D%3E%20%7B%0A%09%09%09%09if%20%28%21stop%29%20resolve%28result%29%2C%20gBrowser.removeTab%28tab%29%2C%20stop%20%3D%20true%3B%0A%09%09%09%7D%0A%09%09%09setTimeout%28destroy%2C%20500%29%3B%0A%09%09%09try%20%7B%0A%09%09%09%09tab.linkedBrowser.addEventListener%28%22DOMContentLoaded%22%2C%20async%20e%20%3D%3E%20%7B%0A%09%09%09%09%09var%20sheet%20%3D%20this.getSheet%28e.target%2C%20this.contentSheetURL%29%3B%0A%09%09%09%09%09if%20%28sheet%29%20result%20%3D%20await%20this.reload%28sheet%2C%20obj%29%3B%0A%09%09%09%09%09destroy%28%29%3B%0A%09%09%09%09%7D%2C%20%7Bonce%3A%20true%7D%29%3B%0A%09%09%09%7D%20catch%28ex%29%20%7B%0A%09%09%09%09destroy%28%29%3B%0A%09%09%09%7D%0A%09%09%7D%29%3B%0A%09%7D%2C%0A%09getSheet%28doc%2C%20href%29%20%7B%0A%09%09var%20sheets%20%3D%20InspectorUtils.getAllStyleSheets%28doc%29%3B%0A%09%09return%20sheets.find%28sheet%20%3D%3E%20sheet.href%20%3D%3D%20href%29%3B%0A%09%7D%2C%0A%09get%20contentSheetURL%28%29%20%7B%0A%09%09var%20file%20%3D%20Services.dirsvc.get%28%22UChrm%22%2C%20Ci.nsIFile%29%3B%0A%09%09file.append%28%22userContent.css%22%29%3B%0A%09%09if%20%28%21file.exists%28%29%29%20return%20null%3B%0A%09%09delete%20this.contentSheetURL%3B%0A%09%09return%20this.contentSheetURL%20%3D%20Services.io.newFileURI%28file%29.spec%3B%0A%09%7D%2C%0A%09get%20restyle%28%29%20%7B%0A%09%09var%20sss%20%3D%20Cc%5B%22@mozilla.org/content/style-sheet-service%3B1%22%5D.getService%28Ci.nsIStyleSheetService%29%3B%0A%09%09var%20uri%20%3D%20Services.io.newURI%28%22data%3Atext/css%2C%3Aroot%7B%7D%22%29%2C%20type%20%3D%20sss.USER_SHEET%3B%0A%09%09delete%20this.restyle%3B%20return%20this.restyle%20%3D%20delay%20%3D%3E%20setTimeout%28%28%29%20%3D%3E%20%7B%0A%09%09%09sss.loadAndRegisterSheet%28uri%2C%20type%29%3B%0A%09%09%09sss.unregisterSheet%28uri%2C%20type%29%3B%0A%09%09%7D%2C%20delay%29%3B%0A%09%7D%2C%0A%09get%20chromeSheet%28%29%20%7B%0A%09%09var%20file%20%3D%20Services.dirsvc.get%28%22UChrm%22%2C%20Ci.nsIFile%29%3B%0A%09%09file.append%28%22userChrome.css%22%29%3B%0A%09%09if%20%28%21file.exists%28%29%29%20return%20null%3B%0A%0A%09%09var%20href%20%3D%20Services.io.newFileURI%28file%29.spec%3B%0A%09%09var%20sheet%20%3D%20this.getSheet%28document%2C%20href%29%3B%0A%09%09if%20%28%21sheet%29%20return%20null%3B%0A%0A%09%09delete%20this.chromeSheet%3B%20return%20this.chromeSheet%20%3D%20sheet%3B%0A%09%7D%0A%7D%29%3B%0A%5D%5D%3E%3C/initcode%3E%0A%20%20%3Ccode%3E%3C%21%5BCDATA%5B/*CODE*/%5D%5D%3E%3C/code%3E%0A%20%20%3Caccelkey%3E%3C%21%5BCDATA%5B%5D%5D%3E%3C/accelkey%3E%0A%20%20%3Chelp%3E%3C%21%5BCDATA%5B%28%28href%2C%20data%29%20%3D%3E%20%7B%0A%09var%20en%20%3D%20Services.ww.getWindowEnumerator%28null%29%3B%0A%09if%20%28%21en.hasMoreElements%28%29%29%20return%3B%0A%09var%20doc%20%3D%20en.getNext%28%29.document%3B%0A%09Cu.importGlobalProperties%28%5B%22InspectorUtils%22%5D%29%3B%0A%0A%09var%20reload%20%3D%20sheet%20%3D%3E%20%7B%0A%09%09var%20style%20%3D%20data%5Bsheet.href%5D%3B%20if%20%28%21style%29%20return%3B%0A%0A%09%09InspectorUtils.parseStyleSheet%28sheet%2C%20style%29%3B%0A%09%09for%28var%20ind%20%3D%200%2C%20len%20%3D%20sheet.cssRules.length%3B%20ind%20%3C%20len%3B%20ind++%29%20%7B%0A%09%09%09var%20rule%20%3D%20sheet.cssRules.item%28ind%29%3B%0A%0A%09%09%09rule.type%20%3D%3D%20rule.IMPORT_RULE%0A%09%09%09%26%26%20rule.styleSheet.href.startsWith%28%22file%3A///%22%29%0A%09%09%09%26%26%20reload%28rule.styleSheet%29%3B%0A%09%09%7D%0A%09%7D%0A%09var%20sheet%20%3D%20InspectorUtils.getAllStyleSheets%28doc%29.find%28sheet%20%3D%3E%20sheet.href%20%3D%3D%20href%29%3B%0A%09if%20%28sheet%29%20reload%28sheet%29%3B%0A%7D%29%28%22%5D%5D%3E%3C/help%3E%0A%20%20%3Cattributes/%3E%0A%3C/custombutton%3E

Отсутствует

 

№1259425-05-2018 22:49:34

unter_officer
Участник
 
Группа: Members
Откуда: Санкт-Петербург
Зарегистрирован: 27-03-2011
Сообщений: 595
UA: Firefox 47.0

Re: Custom Buttons

Dumby пишет
unter_officer пишет

Исправьте пожалуйста кнопку под [firefox] 60+

Там создаётся элемент "statusbarpanel", который
больше не представляет из себя ничего особенного.
Попробуй создавать что-нибудь другое, например, "label",
и тогда, соответственно, вместо tabCounter.label = ...
tabCounter.value = ...

Dumby, большое спасибо за помощь.


«The Truth Is Out There»

Отсутствует

 

№1259526-05-2018 09:05:32

Garalf
Участник
 
Группа: Members
Зарегистрирован: 19-09-2017
Сообщений: 315
UA: Firefox 60.0

Re: Custom Buttons

Dumby
Под вашим четким руководством QTranslate заработал как часы.
И если можно, еще одну полезную кнопку поправить

Выделить код

Код:

self._handleClick =()=> menuPopup.showPopup(this, -1, -1, "popup", "bottomleft", "topleft");


var array = [
   [ "Экспорт закладок в HTML-файл", "setPathAndExportsBookmarksToHTMLFile()", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAADg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////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AAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAHKsv/xS9Lv8Xmyv/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAF5sr/xebK/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAF5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAg9/AAIPPwACDx8AAg8PAAIABwACAAMAAgAHAAIADwACAA8AAgAHAAIAAwACAAcAAg8PAAIPHwACDz8AAg9/AAP//wAA="],
   [ "Импорт закладок из HTML-файла", "importBookmarksOutHTMLFile()", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAADg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8OD+j/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////w4P6P81Kuj/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////////Dg/o/xwT5f9EQv/9Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////8OD+j/JSHa/zM08f80Mvn/RUL5/1pW/f9YU///UU///0lI//9AQPr/Njfw/y0w5P8UFuf/AAAAAAAAAAAAAAAA/////w4P6P8cHcr/NDbb/Tw94v85TtP9F5sr/zk0+f9CPv/9PDn+/zQx/f0qKPj/Hh7v/RQV4v8QEeb9AAAAAAAAAAAAAAAA//////////8OD+j/Hx/D/yVDqf8Xmyv/F5sr/zk0+f85NPn/MjD1/ysq9f8kJPX/Hh7x/xcY6f8OD+j/AAAAAAAAAAAAAAAA////////////////Dg/o/xebK/838l/9F5sr/w4P6P8OD+j/Dg/o/w4P6P8OD+j/Dg/o/w4P6P8OD+j/AAAAAAAAAAAAAAAA////////////////F5sr/x/tRf88/17/QuJf/23Yfv+s/Lj/qPyz/6T8rv+g+ar/m/Sk/5bwn/99xID/AAAAAAAAAAAAAAAA//////////8Xmyv/Kt1J/znvVf85+Vn/Qf9j/0r/a/9E/2j/Qf9k/zv9Xf8y91P/KexI/x/kPf8DkBT/AAAAAAAAAAAAAAAA/////xebK/8axzf/MtZL/TrhU/9B71z9Rvpk/0f+Z/9F/Wf9Pv9h/zX+WP0p+k7/IvNE/RjpOP8HlBn9AAAAAAAAAAAAAAAA//////////8Xmyv/FMIy/zHWSP844FH/CZgc/wmYHP8JmBz/CZgc/wmYHP8JmBz/CZgc/wmYHP8JmBz/AAAAAAAAAAAAAAAA////////////////F5sr/w28LP8w10j9KL08/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////xebK/8UvS7/HKsv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8Xmyv/F5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAF5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgv/AAID/wACA/8AAgP/AAIAAwACAAMAAgADAAIAAwACAAMAAgADAAIAAwACAAMAAgP/AAID/wACA/8AAgv/AAP//wAA="],  
   [ "separator" ],
   [ "Открыть папку для экспорта закладок", "openBookmarksFolder()", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAABAAAAAWAAAAFQAAABQAAAAUAAAAEwAAABIAAAASAAAAEQAAABAAAAAPAAAADwAAAA4AAAALAAAAAwAAAAAAAAAHAAAALAAAAFUAAABjAAAAYgAAAGEAAABgAAAAYAAAAF0AAABcAAAAWwAAAFsAAABYAAAAVwAAAFYAAABJAAAAKAAAAAcAAAAXCgoKbomJid+Tk5PpkJCQ6I2NjeaLi4vjioqK4oWFhd+FhYXffX193H5+ftt1dXXYc3Nz2HFxcdVoaGjKBAQEawAAABoAAAAhgICAxcTExP++vr7/vr6+/76+vv++vr7/vr6+/76+vv+/v7//v7+//7+/v//AwMD/wMDA/8DAwP/Gxsb/j4+P0wAAACYAAAAjkpKSz8zMzP/Hx8f9x8fH/8fHx/3Hx8f9x8fH/cfHx/3Hx8f/x8fH/cfHx/3Hx8f9x8fH/8fHx/3Jycn/sbGx4gAAACkAAAAkm5ub0tjY2P/T09P909PT/9PT0/3T09P+09PT/tPT0/3T09P/09PT/dPT0/7T09P909PT/9PT0/3W1tb/tbW13wAAACcAAAAloqKi1OHh4f/c3Nz93Nzc/9zc3P3c3Nz+3Nzc/tzc3P3c3Nz/3Nzc/dzc3P7c3Nz93Nzc/9zc3P3g4OD/tra23QAAACYAAAAmqamp1+fn5//i4uL94uLi/+Li4v3i4uL94uLi/eLi4v3i4uL/4uLi/eLi4v3i4uL94uLi/+Li4v3m5ub/s7Oz2gAAACYAAAAnt7e32uzs7P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/o6Oj/6Ojo/+jo6P/t7e3/r6+v1wAAACUAAAAnw8PD3fHx8f/t7e397e3t/+3t7f3t7e397e3t/e3t7f3t7e3/7e3t/e3t7f3t7e397e3t/+3t7f3y8vL/sLCw0wAAACEAAAApy8vL3/b29v/y8vL98vLy//Ly8v3y8vL+8vLy/vHx8f3x8fH/9PT0//T09P/09PT/9PT0//Ly8v77+/v/tra2xQAAABIAAAAl19fX4fr6+v/39/f99/f3//f39/339/f99/f3/v7+/v//////7Ozs6OPj4+Xl5eXo6+vr6v///+/s7OzfJCQkRBEREQMAAAAT0tLS0P///////////////////////////////7y8vL0JCQktCgoKCQ4ODgcMDAwHERERCBMTEwkREREEMzMzAQAAAAAPDw8EGxsbOcTExL3Pz8/Ozs7Oz9DQ0NPFxcXCYGBgbgAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALi4uAR0dHQEREREEEhISBRAQEAMaGhoCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAB/wACB/8AA///AAP//wAA="],
   [ "Экспорт закладок в HTML без запроса", "exportsBookmarksToHTMLFile()", "data:image/x-ic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zs7P/s7Oz/+fn5/zMzM7j5+fn/7Ozs/+7u7v/l5eX3AAAAdoODg7Lq6urmUFBQmwQEBIr5+fn//f39/wAAAEgKCgpN//////Hx8f/x8fH//Pz8/0RERMH8/Pz/8fHx//Hx8f/4+Pj/vb294wAAAJAAAAB6GRkZnN3d3fH09PT//////wAAAEYFBQU3//////X19f/19fX/9fX1///////4+Pj/+Pj4//j4+P/4+Pj//f39//////////////////v7+//4+Pj//////wAAAC8AAAAKfn5+j/39/fn5+fn//Pz8/+Pj4+Pd3d3X3d3d193d3dfd3d3X3d3d193d3dfd3d3X3d3d193d3dfj4+PYeHh4ggcHBwkAAAAAAAAACZubm6b//////////gAAAC0FBQUGDQ0NBA4ODgQNDQ0EDQ0NBA0NDQQNDQ0EDQ0NBA0NDQQaGhoCAAAAAAAAAAAAAAAAFxcXARkZGQs3NzcwISEhHSkpKQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAwACD/8AA///AAP//wAA=" ]
];
var menuPopup = self.appendChild(document.createElement("menupopup"));
array.forEach((m,i)=> {
   if ( m[0] == "separator" ) { menuPopup.appendChild(document.createElement("menuseparator")); return };
   var mItem = menuPopup.appendChild(document.createElement("menuitem"));
   mItem.setAttribute("label", m[0]);
   mItem.setAttribute("class", "menuitem-iconic");
   mItem.setAttribute("image", m[2]); 
   mItem.addEventListener("command", ()=> eval(m[1]));
});
menuPopup.setAttribute("onclick", "event.stopPropagation()");


function importBookmarksOutHTMLFile() {
   var fp = window.makeFilePicker();
   fp.init(window, "Выберите HTML-файл для импорта закладок", fp.modeOpen);
   fp.appendFilters(fp.filterHTML);
   Cu.import("resource://gre/modules/FileUtils.jsm");
   fp.displayDirectory = FileUtils.File(getPathToBookmarksFolder());
   fp.open(re=> { 
      if ( re != fp.returnOK ) return;
      
      Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
      BookmarkHTMLUtils.importFromFile(fp.file.path).then(null, Cu.reportError);
   })
};


function exportsBookmarksToHTMLFile() {
   var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
   file.initWithPath(getPathToBookmarksFolder());
   var path = file.path + "\\bookmarks-" + (new Date()).toLocaleFormat("%Y.%d.%m") + ".html";

   Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
   BookmarkHTMLUtils.exportToFile(path).then(null, Cu.reportError);

   var alertsService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService)
   alertsService.showAlertNotification(self.image, self.label, "Экспортировал закладки как HTML в " + path);
   setTimeout(()=> alertsService.closeAlert(), 3500);
};


function openBookmarksFolder() {
   var folder = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
   folder.initWithPath(getPathToBookmarksFolder());
   folder.launch();
};


function setPathAndExportsBookmarksToHTMLFile() {     
   var fp = window.makeFilePicker();
   fp.init(window, "Укажите папку для экспорта закладок!", fp.modeGetFolder);
   fp.open(re=> { 
      if ( re != fp.returnOK ) return;
      cbu.setPrefs("CB.exportsBookmarksToHTMLFile.path", convertFromUnicode("UTF-8", fp.file.path));
      
      exportsBookmarksToHTMLFile();
   })
};


function getPathToBookmarksFolder() {     
   try { return Services.prefs.getComplexValue("CB.exportsBookmarksToHTMLFile.path", Ci.nsISupportsString).data } 
   catch(e) { return "C:" };
};


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


this.onmouseover =()=> { 
   var path = getPathToBookmarksFolder();
   this.tooltipText = self.label + "\nЛ: Меню кнопки\nП: CB меню\n\nПапка для экспорта:\n" + path;
};

Отсутствует

 

№1259626-05-2018 11:35:37

drage2
Забанен
 
Группа: Members
Откуда: Донецк
Зарегистрирован: 23-11-2017
Сообщений: 392
UA: Firefox 60.0

Re: Custom Buttons

Garalf пишет

Под вашим четким руководством QTranslate заработал как часы.

Толком скажи, что за код?, в 60 работает?
Эту бы поправить.....Это- вещь! в 60 - падает...И СВ выше 60 - кранты? .Шо, никто не знает?

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

Выделить код

Код:

// Translate от 27.02.2017. ...............

// Настройка функций кликов мыши для кнопки ...............
this.onclick =e=> {
   if ( e.button == 0 ) {         
        var sel = getSelect();
        sel ? translateText(sel) : translatePage();    
        }
                    
   if ( e.button == 1 )
        translateText(gClipboard.read(), true);
          
   if ( e.button == 2 && !e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey ) { 
        e.preventDefault();  
        menu.showPopup(self, -1, -1, "popup", "bottomleft", "topleft");
        } 
};
this.oncontextmenu =e=> { e.button && !e.ctrlKey && e.preventDefault() };


var background = 'white', fontSize = 'medium'; // фон и размер шрифта окошка перевода
var winWidth = 0.4, winHeight = 0.4;          // ширина и высота окошка перевода относительно размера страницы


// Создать меню ...............
var array = [    
    { label: "Перевод текста в маленьком окошке", checkbox: '', value: 'Translate.textInPopup' },
    { label: "Перевод текста в двойным правым кликом", checkbox: '', value: 'Translate.textWithDoubleRightClick' },              
    { label: "Перевод страницы в новой вкладке сразу справа", checkbox: '', value: 'Translate.nextPage' },
    { label: "Перевод выделенного текста из контекстного меню", checkbox: '', value: 'Translate.textFromContextMenu' },              
    { separator: ''},
    { label: "Удалять подсказки в переводчиках", checkbox: '', value: 'Translate.noTooltipForTranslate', func: '' },
    { label: "Удалять панель управления в переводчике Googlе", checkbox: '', value: 'Translate.removeGoogleTranslatorHeader', func: '' },
    { separator: ''},
    { label: "Перевод страницы в обычном переводчике Google", radio: '', value: 'google' },    
    { label: "Перевод страницы с заменой текста в переводчике Google", radio: '', value: 'googleBookmarklet' }
            ];
var menu = self.appendChild( document.createElement("menupopup") );  
array.forEach((m)=> {
   if ( "separator" in m ) { menu.appendChild( document.createElement("menuseparator") ); return };
   var mItem = document.createElement("menuitem");
   mItem.setAttribute("label", m.label);
   
   if ( "radio" in m ) { 
        mItem.setAttribute("type", "radio");
        mItem.setAttribute('checked', cbu.getPrefs("Translate.pageIn") == m.value );
        mItem.onclick =()=> cbu.setPrefs("Translate.pageIn", m.value);  
        }  
   if ( "checkbox" in m ) {          
        mItem.setAttribute('type', 'checkbox');
        mItem.setAttribute('checked', cbu.getPrefs(m.value) );
        mItem.onclick =()=> cbu.setPrefs(m.value, !cbu.getPrefs(m.value));  
        }
   if ( "func" in m ) mItem.addEventListener("command", ()=> toggleGoogleTranslatorStyle());
       
   menu.appendChild(mItem);
});
menu.setAttribute("onclick", "event.stopPropagation()");


// Получить выделенный текст из страницы или false ...............
function getSelect() {
   var sel = gBrowser.contentDocument.defaultView.getSelection();
   return (sel == '') ? false : sel.toString();
};


// Удалить панель управления в переводчике Googlе и подсказки в переводчиках ...............
function toggleGoogleTranslatorStyle(arg) {
   var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
   try { sss.unregisterSheet( self.uri, 0) } catch(e) {};
   
   if ( cbu.getPrefs("Translate.removeGoogleTranslatorHeader") ) {  // панель управления
        var removeHeader = '\
            @-moz-document domain("translate.google.com") {\
               #gb, #gt-bbar, #gt-c:not([class="g-section"]) { display: none !important; }\
               #contentframe { top: 0 !important; }\
            }';           
        }
   
   if ( cbu.getPrefs("Translate.noTooltipForTranslate") ) {  // подсказки в переводчиках
        var noPopup = '\
            /*Microsoft*/\
            DIV[translate="no"] { display: none !important; }\
            *[lang="ru"] {\
            color: black !important;\
            background-color: transparent !important;\
            }\
            /*Google*/\
            @-moz-document domain("translate.google.com") {\
               .jfk-tooltip { display: none !important; }\
            }\
            @-moz-document regexp("^https?://translate\.google\..*") {/**/}\
            @-moz-document domain("translate.googleusercontent.com") {\
              span[onmouseout][onmouseover][style] { background-color: transparent !important; }\
              .gmnoprint { display: none !important; }\
            }\
            .goog-text-highlight {\
            background-color: transparent !important;\
            border: none !important;\
            box-shadow: none !important;\
            }\
            .goog-tooltip.skiptranslate { display: none !important; }\
            ';
        }   
   self.css = removeHeader + noPopup;

   if ( !!self.css ) {
        self.uri = makeURI("data:text/css," + encodeURIComponent(self.css));
        sss.loadAndRegisterSheet(self.uri, 0);
        }
        
   arg && addDestructor(()=> sss.unregisterSheet(self.uri, 0) );  
};
toggleGoogleTranslatorStyle(true); 


// Перевод страницы ...............   
function translatePage() {
   var translator = cbu.getPrefs("Translate.pageIn");
   
   // перевод страницы в обычном переводчике Google в новой активной вкладке или текущей вкладке
   if ( translator == "google" ) {
        var url = "http://translate.google.com/translate?u=" + content.location + "&hl=ru&ie=UTF-8&sl=auto&tl=ru";
        cbu.getPrefs("Translate.nextPage")
        ? gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), gBrowser.mCurrentTab._tPos + 1)
        : loadURI(url);
        return;
        } 

   // перевод страницы с заменой текста на странице в переводчике Microsoft или Google 
   if ( cbu.getPrefs("Translate.nextPage") ) {
        gBrowser.getBrowserForTab(gBrowser.selectedTab = gBrowser.duplicateTab(gBrowser.mCurrentTab))
           .addEventListener("pageshow", function c(e) {
               this.removeEventListener(e.type, c);
               runBukmarklet();
           });              
        }    
   else runBukmarklet();
   
   // запустить букмарклет для перевода
   function runBukmarklet() {
      cbu.setPrefs("security.mixed_content.block_active_content", false);
      
      content.document.location = "javascript:{var d=document; var b=d.body; var o=d.createElement('script');o.setAttribute('src','http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit&hl=ru');o.setAttribute('type','text/javascript');b.appendChild(o); var v=b.insertBefore(d.createElement('div'),b.firstChild);v.id='google_translate_element';v.style.display='none'; var p=d.createElement('scri'+'pt');p.text='function%20googleTranslateElementInit(){var%20tElem%20=%20new%20google.translate.TranslateElement({pageLanguage:%22%22},%22google_translate_element%22);setTimeout(function()%20{%20tElem.showBanner(true);%20},100);}';p.setAttribute('type','text/javascript');b.appendChild(p);}void%200";
   } 
};


// Обработчик следит за двойным правым кликом мыши на странице и запускает перевод выделенного текста ...............
addEventListener("dblclick", e=> {
   if ( e.button && cbu.getPrefs("Translate.textWithDoubleRightClick") ) {
        e.preventDefault();
        document.getElementById("contentAreaContextMenu").hidePopup();

        translateText(getSelect());
        }
}, false, gBrowser);


// Перевод выделенного текста из контекстного меню ...............   
var contextMenu = document.getElementById("contentAreaContextMenu");
var mItem = contextMenu.insertBefore(document.createElement("menuitem"), contextMenu.children[1]);
mItem.setAttribute("label", "Перевод выделенного текста");
mItem.setAttribute("class", "menuitem-iconic");
mItem.setAttribute("image", "data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOWYi0zLy8ui0NDQnNPT05zV1dWc1dXVnuXj45gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADhdWXExZCI/9ja2v/b29v/3d3d/97e3v/l5ub/6+rqmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvl5O/7JFM//Cn5z/1tbW/9nZ2f/a2tr/4eHh/93d3Z4AAAAA/5FPnvCHSqbyiEik8ohIpPKISKTwhkek94tXutVvRP/SbkP/0mIu/9LCvv/c3d7/2dnZ/+Hh4f/h4eGc/5FNlv+RTv/7jkz/+o5M//qOTP/6jUv/+o1L//iMSv/2i0n/94tI//SHQv/V1tn/u7eu/6mik//l5eb/4eHhnPSLTJ77jk7/9YtM//WLTP/1i0v/9YtL//SKSv/0ikr/9IpJ//aJR//Uil//mZOC/6ihkv/h4uP/4+Pj/+Hh4Zz2jEyc+49O//WMTP/1iET/9YQ6//WDOv/1h0P/9YtL//SKSv/3iEL/yKaU/4mAaP/AvLT/3t7f/+bm5v/l5eWc9o1OnPuQUP/1hkD/8r6k/+/z8//v8/T/8sCn//WFP//1i0r/945P/6eimf/k5ef/mI56/+Tk5f/r7Oz/5eXlnPaNT5z7jkz/9Kh///Do4//1hTz/9nsj//Dm4P/0oXP/+IlH/9KEVf+blYf/o5qL/5WJcf+ajnb/2tjT/+fn6Zz2j0+c+41J//LHs//yu57/9oE0/+/x7//v8fH/87WV//eFO//YuKv/293f/7Gqnf/r7O3/5+fn/+vr6//l5eWc9o9RnPuQTv/zqoH/8Ofj//WGPf/1hDv/9YhE//WJRv/0iUb/z8/R/+Hh4f/q6+v/5ubm/+Xl5v/q6ur/5OTknvaPU5z7klT/9YlF//LAp//v8/T/7/T1//O0k//2iET/6KJ+/+Lk5f/v7+//7Ozs/+vr6//r6+v/8PDw//Ty8pj2kVOc+5NU//WQUv/1i0r/9YdB//WGP//1i0n/+o5M//3CpLLo7e6k6OjopOfn56Tn5+ek5OTkpvT09J4AAAAA9JBUnvuTVf/1kFP/9ZBS//WPUv/1j1H/9Y5Q//+UU/oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP+WWJb/l1n/+5NW//uTVf/7k1T/+5JT//6TU///lFO2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/5ZYlvSQVJ72kVOc9pFTnPaPU5zzjVCi/5VXOgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/4EAAP8AAAD/AAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAD/AAAA/wAAgf8AAA=="); 
mItem.onclick =()=> translateText(getSelect());
addEventListener("popupshowing", ()=> {
   mItem.hidden = !cbu.getPrefs("Translate.textFromContextMenu") || !gContextMenu.isTextSelected; 
}, false, contextMenu);
addDestructor(()=> mItem.remove());


// Перевести текст в Google переводчике в новой вкладке сразу справа или в маленьком окошке ...............
function translateText(text, clipboard) {
   if ( text == false ) return;

   // перевод в Google переводчике текста
   if ( !cbu.getPrefs("Translate.textInPopup") ) {
        var url = "http://translate.google.com/translate_t?hl=ru#auto|ru|" + text;
        gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), gBrowser.mCurrentTab._tPos + 1);
        return;
        };

   var beg = "http://translate.google.com/translate_t?prev=hp&hl=ru&js=y&text=";
   var end = "&file=&sl=auto&tl=ru&history_state0=#";
   var url = beg + text + end;
    
   var req = new XMLHttpRequest();
   req.open("GET", url, true);
   
   req.onload =()=> {
       var res = req.responseText;
       var suHTML = Cc["@mozilla.org/feed-unescapehtml;1"].getService(Ci.nsIScriptableUnescapeHTML);
       var doc = document.implementation.createHTMLDocument("");
       doc.body.appendChild(suHTML.parseFragment(res, false, null, doc.body));

       var ruHTML = doc.getElementById("result_box").innerHTML;
       var dataURL = 'data:text/html;charset=utf-8, <html contenteditable/><title>Translate</title>'
       dataURL += '<style>body { background-color: '+ background +'; font-size: '+ fontSize +' }</style>';
       dataURL += ruHTML + '</body></html>';
       
       var width = (0) || winWidth * gBrowser.boxObject.width; 
       var height = (0) || winHeight * gBrowser.boxObject.height;

       // получить координаты кнопки или выделенного текста
       if ( clipboard && cbu.getPrefs("Translate.textInPopup") ) {
            var bcr = self.getBoundingClientRect();
            var posX = bcr.left;
            var posY = bcr.bottom + 5;
            }
       else
            {
            var bcr = gBrowser.contentDocument.defaultView.getSelection().getRangeAt(0).getBoundingClientRect();
            var posX = window.content.mozInnerScreenX + bcr.left;
            var posY = window.content.mozInnerScreenY + bcr.bottom + 5;
            }
       
       var deltaX = posX + width - (fullScreen ? screen.width : screen.availWidth);
       if (deltaX > 0) posX -= deltaX;
       var deltaY = posY + height - (fullScreen ? screen.height : screen.availHeight);
       if (deltaY > 0) posY -= deltaY;     

       var win = window.openDialog(dataURL, "", "outerWidth="+width+", outerHeight="+height+", screenX="+posX+", screenY="+posY+", status=no, scrollbars=yes, resizable=yes");
       win.focus();

       // закрывать окошко перевода кликом на странице                 
       gBrowser.addEventListener("click", function c() {
          this.removeEventListener("click", c);
          win && win.close();                                    
       });
   };
   req.channel.loadFlags |= req.channel.LOAD_FROM_CACHE;
   req.send(null)
};


// Подсказка у кнопки ...............
this.tooltipText = "Translate \nЛ: Перевести страницу / выделенный текст \nС: Перевести текст из буфера обмена \nП: Меню \nДП: CB меню";

Отредактировано drage2 (26-05-2018 11:45:21)

Отсутствует

 

№1259726-05-2018 12:00:02

func4ptch4
Участник
 
Группа: Members
Зарегистрирован: 03-05-2018
Сообщений: 220
UA: Firefox 60.0

Re: Custom Buttons

Dumby Спасибо работает. За QTranslate тоже.

Отредактировано func4ptch4 (26-05-2018 12:03:41)

Отсутствует

 

№1259826-05-2018 19:07:27

Garalf
Участник
 
Группа: Members
Зарегистрирован: 19-09-2017
Сообщений: 315
UA: Firefox 57.0

Re: Custom Buttons

drage2

drage2 пишет

Толком скажи, что за код?, в 60 работает?

В этом коде вызывется утилита QTranslate и автоматом переводит выделенный текст. В 60 теперь работает.

drage2 пишет

Эту бы поправить.....Это- вещь!

У меня есть другой работающий код Там актуальны первые два пункта из контекстного меню.

скрытый текст
/*Initialization Code*/

/*Контекстное меню "Перевод текста"*/
/* https://forum.mozilla-russia.org/viewtopic.php?pid=545785#p545785 */

var mainicon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAArrAAAK6wGCiw1aAAAAKnRFWHRDcmVhdGlvbiBUaW1lAERvIDEgQXByIDIwMDQgMTY6MDY6NDcgKzAxMDAdSRC6AAADPElEQVR42pXT7U9TVxwH8N89SDaFOJYtGkSnG+Ie1IbHdHYmEi1bFDaKJm4NVB4KoanxAYniEhOc6EUQogX1T/DF9mqv9sqYZdELbm4TmAgaBJQKLS1w+w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IwRo5JgamadNngI0beCzqFuiCRYzdkgICADs=";
var lingvicon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACBElEQVR42o2Sy04TYRiGJ+oFtNANKaXFTmmhB+i0DGBpNbIQ2ZpwCV6ArlwYbwA35ZDYHXFjIqh4DCalFKZIoQwWp6YxdlGSSjKLYuyiST28fP9UFPpr9Eue3fs8k0x+Qfh52uWo/P7q+MfCxRi0Y2JRvGNERw32RhkR5CORgtB6hfErn6rJ5NdGo4F/8cLj+c4F8rHot9zkJPbvTkF/9RK1chn1ev2PPO/pARfYGR7CbHs73l4YMdgdGcbexAQ+3LyB/UQCuqLgy+EharUanrlcfCAny5ihwC6FVMaQjB2ZMYjcICMMdWwM1WoVT0UnH9gKh43ASWE7zAhhK0RIErJSELquY8l5ng9s0mCmrc0QtpkQkkgKIhtkDGBzgNGPSqWCJ93dfCBDo2kKZKXTwpt+RgCZAOH3o0w/97HDwQfWacACp4SAHwpJis+HdYbXi1KphEd2Ox9I02DabDa+ovh9TYkExlpfn0G6txfFYhGLXV18YJUGcQoYgrcprJGQNvBg1cNwQ9M0LNhsfCBFg7jZ1CIQbjdSDHo8jHw+j4XOTj6w7HIdxE2m34K7Kaww6OEco6oqHlqtfGDObr+WsFg+p1qEJEMUf7GRyfy4ZbGsCH+7O4Jw5p7NdvuBw7Hx2ulsnJQZ9+fnszQ7K/zPXRKEc1MdHdfnrNblJVGsLQYCB62bI3TCqVl5ZBgZAAAAAElFTkSuQmCC";
var pageurl;
var trtext;
var ctabpos;
//------------------------Page context menu------------------------------------------------- 
(function TranslatePage(){
const kXULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

    var contextMenu = document.getElementById("contentAreaContextMenu");
    var separator = document.getElementById("context-viewsource");
    var eventTarget = null;
    var menu = document.createElementNS(kXULNS, "menu");
    menu.id = "TranslatePage";
    menu.setAttribute("label", "Перевести Страницу");
    menu.setAttribute("class", "menu-iconic");
    menu.setAttribute("image", mainicon);
    menu.hidden = true;
    contextMenu.insertBefore(menu, separator );
    var menuPopup = document.createElementNS(kXULNS, "menupopup");
    menu.appendChild(menuPopup);
var lst = [
       {
          label:"Перевести страницу с Google",
          command: gtr,
          image:gt1icon
        },
         {
          label:"Перевести страницу с Promt ",
          command:promttr,
          image:promticon
        },
        {
          label:"Перевести страницу с Yandex ",
          command:yndtr,
          image:yndicon
        },
        {
          label:"Перевести страницу с Bing Translator",
          command:bingtr,
          image:bingicon
        },
       {
          label:"separator"
        },
        {
          label:"Перевести страницу с Google в новой вкладке",
          command: gtrnew,
          image:gt1icon
        },
         {
          label:"Перевести страницу с Promt в новой вкладке",
          command:promttrnew,
          image:promticon
        },
        {
          label:"Перевести страницу с Yandex в новой вкладке",
          command:yndtrnew,
          image:yndicon
        },
        {
          label:"Перевести страницу с Bing Translator в новой вкладке",
          command:bingtrnew,
          image:bingicon
        }
        ];
   
for(var i = 0, m; m = lst[i]; i++){
    if (m.label=="separator"){
     var menuItem = document.createElementNS(kXULNS, "menuseparator");
         menuItem.id = "TranslatePage" + m.label.toString();
        menuPopup.appendChild(menuItem);
    } else {
        var menuItem = document.createElementNS(kXULNS, "menuitem");
        menuItem.setAttribute("label", m.label);
        menuItem.setAttribute("class", "menuitem-iconic");
        menuItem.setAttribute("image", m.image);
        menuItem.setAttribute("type", "m.radio");
        menuItem.addEventListener("command", m.command, false);
        menuItem.id = "TranslatePage" + m.label.toString();
        menuPopup.appendChild(menuItem);
        }
     } 
    contextMenu.addEventListener("popupshowing", setMenuDisplay, false);
   
function setMenuDisplay(aEvent) {

                 pageurl=encodeURIComponent(content.document.location.href)
                 if (gContextMenu.isTextSelected)
                 {
                 document.getElementById("TranslatePage").hidden = true;
                 }
                 else
                 document.getElementById("TranslatePage").hidden = false;
                   }
   

//--------Перевести страницу с Google--------------
function gtr(){
var url = "http://translate.google.com/translate?hl=ru&ie=UTF8&prev=_t&sl=auto&tl=ru&u="+pageurl;
loadURI(url);
}
//---------Перевести страницу с Promt---------------
function promttr(){
var url = "http://www.translate.ru/siteTranslation/autolink/?direction=ar&template=General&sourceURL="+pageurl;
loadURI(url);
}
//---------Перевести страницу с Yandex---------------
function yndtr(){
var url = "http://translate.yandex.net/translate_f?dir=auto&lang=auto-ru&ui=ru&url="+pageurl;
loadURI(url);
}
//---------Перевести страницу с Bing Translator---------------
function bingtr(){
var url = "http://www.microsofttranslator.com/bv.aspx?from=&to=ru&a="+pageurl;
loadURI(url);
}
//--------Перевести страницу с Google в новой вкладке--------------
function gtrnew(){
var url = "http://translate.google.com/translate?hl=ru&ie=UTF8&prev=_t&sl=auto&tl=ru&u="+pageurl;
getBrowser (). selectedTab = getBrowser (). addTab (url);
}
//---------Перевести страницу с Promt в новой вкладке---------------
function promttrnew(){
var url = "http://www.translate.ru/siteTranslation/autolink/?direction=ar&template=General&sourceURL="+pageurl;
getBrowser (). selectedTab = getBrowser (). addTab (url);
}
//---------ППеревести страницу с Yandex в новой вкладке---------------
function yndtrnew(){
var url = "http://translate.yandex.net/translate_f?dir=auto&lang=auto-ru&ui=ru&url="+pageurl;
getBrowser (). selectedTab = getBrowser (). addTab (url);
}
//---------Перевести страницу с Bing Translator в новой вкладке---------------
function bingtrnew(){
var url = "http://www.microsofttranslator.com/bv.aspx?from=&to=ru&a="+pageurl;
getBrowser (). selectedTab = getBrowser (). addTab (url);
}

})();
(function TranslateSelected(){
const kXULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

    var contextMenu = document.getElementById("contentAreaContextMenu");
    var separator = document.getElementById("context-searchselect");
    var eventTarget = null;
    var menu = document.createElementNS(kXULNS, "menu");
    menu.id = "TranslateSelected";
    menu.setAttribute("label", "Перевести выделенный текст");
    menu.setAttribute("class", "menu-iconic");
    menu.setAttribute("image", mainicon);
    menu.hidden = true;
    contextMenu.insertBefore(menu, separator );
    var menuPopup = document.createElementNS(kXULNS, "menupopup");
    menu.appendChild(menuPopup);
var lst = [
       {
          label:"Заменить выделенный текст переводом",
          command:trsel01,
          image:gt1icon
        },
         {
          label:"Перевести выделенный текст в окне",
          command:trsel02,
          image:gt1icon
        },
       {
          label:"separator"
        },
        {
          label:"Перевести выделенный текст в Google",
          command:trsel03,
          image:gt1icon
        },
        {
          label:"Перевести выделенный текст в PROMT",
          command:trsel04,
          image:promticon
        },
        {
          label:"Перевести выделенный текст в Bing Translator",
          command:trsel05,
          image:bingicon
        },
        {
          label:"separator"
        },
        {
          label:"Перевести выделенное слово в Яндексе",
          command:trsel06,
          image:yndicon
        },
        {
          label:"Перевести выделенное слово в Lingvo",
          command:trsel07,
          image:lingvicon
        },
       
        {
          label:"Перевести выделенное слово в Mail.ru",
          command:trsel08,
          image:maillicon
        }
        ];
   
for(var i = 0, m; m = lst[i]; i++){
    if (m.label=="separator"){
     var menuItem = document.createElementNS(kXULNS, "menuseparator");
         menuItem.id = "TranslateSelected" + m.label.toString();
        menuPopup.appendChild(menuItem);
    }
       else{
        var menuItem = document.createElementNS(kXULNS, "menuitem");
        menuItem.setAttribute("label", m.label);
        menuItem.setAttribute("class", "menuitem-iconic");
        menuItem.setAttribute("image", m.image);
        menuItem.setAttribute("type", "m.radio");
        menuItem.addEventListener("command", m.command, false);
        menuItem.id = "TranslateSelected" + m.label.toString();
        menuPopup.appendChild(menuItem);
        }
    }
    contextMenu.addEventListener("popupshowing", setMenuDisplay, false);
     
    function setMenuDisplay(aEvent) {
                 if (gContextMenu.isTextSelected)
                 {
                 var doc = getBrowser (). contentDocument;
                 trtext = doc. defaultView. getSelection ();
                 ctabpos = gBrowser.mCurrentTab._tPos +1;
                                  document.getElementById("TranslateSelected").hidden = false;
                 }
                 else
                 document.getElementById("TranslateSelected").hidden = true;
                   }
                   
//----------Заменить текст переводом------------
function trsel01(){
var fullUrl = "http://translate.google.hu/translate_t?text="+trtext+"&hl=ru"+"&langpair=auto|ru&tbb=1" ;
       function removeHTMLTags(mitkell) {  //clean up a string from html tags
       var strInputCode = mitkell;
       var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
       return strTagStrippedText;
                                        }
           function infoReceived() {  // if there is response from Google then write out translation
           
           var output = httpRequest.responseText;
           if (output.length) {
             // Build the output string from Google Page
             output = output.replace(/&quot;/gi,'"');
             output = output.replace(/&lt;/gi,'<');
             output = output.replace(/&gt;/gi,'>');
             output = output.replace(/&amp;/gi,'&');
             output = output.replace(/'/gi,"'");
             var fieldArray = output.split('</head>');
             if (fieldArray[1].search('class="short_text"')!=-1) {
                var tempResz = fieldArray[1].split('<span id=result_box class="short_text">');
             }
             else if (fieldArray[1].search('class="medium_text"')!=-1) {
                var tempResz = fieldArray[1].split('<span id=result_box class="medium_text">');
             }
             else {
                var tempResz = fieldArray[1].split('<span id=result_box class="long_text">');
             }
             var kimenet = tempResz[1].split('</span></div>');
             var range = content.getSelection().getRangeAt(0);
             range.deleteContents();
             range.insertNode(document.createTextNode(removeHTMLTags(kimenet[0])));
           }
        }

        httpRequest = new XMLHttpRequest();
        httpRequest.open("GET", fullUrl, true);
        httpRequest.onload = infoReceived;
        httpRequest.send(null);
}   

//----------Перевести выделенный текст в окне------------
function trsel02(){
var url1="http://translate.google.com/translate_t?prev=hp&hl=ru&js=y&text=";
var url2="&file=&sl=en&tl=ru&history_state0=#";
var urltr=url1+trtext+url2;

var xmlhttp
function gettransdata()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }

xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",urltr,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  var trin=xmlhttp.responseText;

var chkpoint='<span id=result_box';
var arrayOfStrings = trin.split(chkpoint);

var trouttmp=arrayOfStrings[1];
var chkpoint='<div id=spell-place-holder';
var arrayOfStrings = trouttmp.split(chkpoint);

trouttmp1=arrayOfStrings[0];
trouttmp2=trouttmp1.replace(/<span.+?">/g,"")
trouttmp2=trouttmp2.replace(/<\/span>/g,"")
trouttmp2=trouttmp2.replace(/class="long_text">/g,"")
trouttmp2=trouttmp2.replace(/class="short_text">/g,"")
trouttmp2=trouttmp2.replace(/class="medium_text">/g,"")
trouttmp2=trouttmp2.replace(/<br><\/div><\/div>/g,"")

var jurl='data:text/html,<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"><html><head><title></title><meta charset="utf-8"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'+trouttmp2+'</body></html>';

var sizex = screen.width/2.2
var sizey = screen.height/2.2
var posx=screen.width-sizex;
var posy=screen.height-sizey;
var wnd = window.open(jurl, this.name, "width="+(sizex-30)+",height="+(sizey-87)+",screenX="+posx+",screenY="+posy+",status=no,scrollbars=yes,resizable=yes");
if (wnd.focus) {
  wnd.focus(); };

  }
}

function GetXmlHttpObject(){
if (window.XMLHttpRequest)
  { return new XMLHttpRequest();}
if (window.ActiveXObject)
  { return new ActiveXObject("Microsoft.XMLHTTP");}
return null;
}
gettransdata();

}     
//--------Перевести текст в Google--------------
function trsel03(){
var url="http://translate.google.com/translate_t?hl=ru#auto|ru|"+trtext;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), ctabpos);
}

//---------Перевести текст в PROMT---------------
function trsel04(){
var url="http://www.translate.ru/?External=IE8Accelerator&formEncoding=utf-8&direction=ar&prmtlang=ru&status=translate&template=General&source="+trtext;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), ctabpos);
}

//---------Перевести текст в Bing Translator---------------
function trsel05(){
var url="http://www.microsofttranslator.com/?ref=IE8Activity&to=ru&SourceText="+trtext;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), ctabpos);
}
//----------Перевести слово в Яндексе------------
function trsel06(){
var urltr="http://translate.yandex.ru/tr.json/translate?callback=json.c(6)&lang=en-ru&text="+trtext;

var xmlhttp
function gettransdata()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }

xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",urltr,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  var tryain=xmlhttp.responseText;
tryain=tryain.replace(/json\.c\(6\)/g,"")
tryain=tryain.slice(2,-2)

var jurl='data:text/html,<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"><html><head><title></title><meta charset="utf-8"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'+tryain+'</body></html>';

var sizex = screen.width/2.2
var sizey = screen.height/2.2
var posx=screen.width-sizex;
var posy=screen.height-sizey;
var wnd = window.open(jurl, this.name, "width="+(sizex-30)+",height="+(sizey-87)+",screenX="+posx+",screenY="+posy+",status=no,scrollbars=yes,resizable=yes");
if (wnd.focus) {
  wnd.focus(); };
  }
}

function GetXmlHttpObject(){
if (window.XMLHttpRequest)
  { return new XMLHttpRequest();}
if (window.ActiveXObject)
  { return new ActiveXObject("Microsoft.XMLHTTP");}
return null;
}
gettransdata();

}

//-----------Перевести слово в Lingvo--------------
function trsel07(){
var url="http://lingvopro.abbyyonline.com/ru/Search/en-ru/"+trtext;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), ctabpos);
}

//----------Перевести слово в Mail.ru------------
function trsel08(){
var url="http://lingvo.mail.ru/?lang_id=1033&translate=&text="+trtext;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab(url), ctabpos);
}



})();

/* https://forum.mozilla-russia.org/viewtopic.php?pid=545785#p545785 */
/*Контекстное меню "Перевод текста"*/

Отредактировано Garalf (26-05-2018 19:17:21)

Отсутствует

 

№1259928-05-2018 12:36:02

Dumby
Участник
 
Группа: Members
Зарегистрирован: 12-08-2012
Сообщений: 2242
UA: Firefox 52.0

Re: Custom Buttons

Garalf пишет

И если можно, еще одну полезную кнопку поправить

:/

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

Выделить код

Код:

(obj => {
    this._handleClick = () => obj.popup.openPopup(this, "after_start");
    this.onmouseenter = e => this.tooltipText = this.label +
        "\nЛ: Меню кнопки\nП: CB меню\n\nПапка для экспорта:\n" + (obj.path || "Не установлено.");
    addDestructor(reason => reason == "delete" && Services.prefs.clearUserPref(obj.pref));
})({
    get popup() {
        var popup = document.createElement("menupopup");
        popup.setAttribute("oncommand", "linkedObject[event.target.value]();");
        popup.linkedObject = this;
        var keys = ["label", "value", "image"];
        for(var data of [
            ["Экспорт закладок в HTML-файл", "export", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAADg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAADg/o/w4P6P8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAADg/o/zUq6P8OD+j/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAADg/o/0RC//0cE+X/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAA/////xQW5/8tMOT/Njfw/0BA+v9JSP//UU///1hT//9aVv3/RUL5/zQy+f8zNPH/JSHa/w4P6P8AAAAAAAAAAAAAAAAAAAAA/////xAR5v0UFeL/Hh7v/Soo+P80Mf39PDn+/0I+//05NPn/F5sr/zlO0/08PeL/NDbb/Rwdyv8OD+j/AAAAAAAAAAAAAAAA/////w4P6P8XGOn/Hh7x/yQk9f8rKvX/MjD1/zk0+f85NPn/F5sr/xebK/8lQ6n/Hx/D/w4P6P8AAAAAAAAAAAAAAAAAAAAA/////w4P6P8OD+j/Dg/o/w4P6P8OD+j/Dg/o/w4P6P8OD+j/F5sr/zfyX/0Xmyv/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAA/////33EgP+W8J//m/Sk/6D5qv+k/K7/qPyz/6z8uP9t2H7/QuJf/zz/Xv8f7UX/F5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAA/////wOQFP8f5D3/KexI/zL3U/87/V3/Qf9k/0T/aP9K/2v/Qf9j/zn5Wf8571X/Kt1J/xebK/8AAAAAAAAAAAAAAAAAAAAA/////weUGf0Y6Tj/IvNE/Sn6Tv81/lj9Pv9h/0X9Z/1H/mf/Rvpk/0HvXP064VP/MtZL/RrHN/8Xmyv/AAAAAAAAAAAAAAAA/////wmYHP8JmBz/CZgc/wmYHP8JmBz/CZgc/wmYHP8JmBz/CZgc/zjgUf8x1kj/FMIy/xebK/8AAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAKL08/zDXSP0NvCz/F5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAHKsv/xS9Lv8Xmyv/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAF5sr/xebK/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAAAAAAAAAAAAAAAAAF5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAg9/AAIPPwACDx8AAg8PAAIABwACAAMAAgAHAAIADwACAA8AAgAHAAIAAwACAAcAAg8PAAIPHwACDz8AAg9/AAP//wAA="],
            ["Импорт закладок из HTML-файла", "import", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAADg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8OD+j/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////w4P6P81Kuj/Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////////Dg/o/xwT5f9EQv/9Dg/o/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////8OD+j/JSHa/zM08f80Mvn/RUL5/1pW/f9YU///UU///0lI//9AQPr/Njfw/y0w5P8UFuf/AAAAAAAAAAAAAAAA/////w4P6P8cHcr/NDbb/Tw94v85TtP9F5sr/zk0+f9CPv/9PDn+/zQx/f0qKPj/Hh7v/RQV4v8QEeb9AAAAAAAAAAAAAAAA//////////8OD+j/Hx/D/yVDqf8Xmyv/F5sr/zk0+f85NPn/MjD1/ysq9f8kJPX/Hh7x/xcY6f8OD+j/AAAAAAAAAAAAAAAA////////////////Dg/o/xebK/838l/9F5sr/w4P6P8OD+j/Dg/o/w4P6P8OD+j/Dg/o/w4P6P8OD+j/AAAAAAAAAAAAAAAA////////////////F5sr/x/tRf88/17/QuJf/23Yfv+s/Lj/qPyz/6T8rv+g+ar/m/Sk/5bwn/99xID/AAAAAAAAAAAAAAAA//////////8Xmyv/Kt1J/znvVf85+Vn/Qf9j/0r/a/9E/2j/Qf9k/zv9Xf8y91P/KexI/x/kPf8DkBT/AAAAAAAAAAAAAAAA/////xebK/8axzf/MtZL/TrhU/9B71z9Rvpk/0f+Z/9F/Wf9Pv9h/zX+WP0p+k7/IvNE/RjpOP8HlBn9AAAAAAAAAAAAAAAA//////////8Xmyv/FMIy/zHWSP844FH/CZgc/wmYHP8JmBz/CZgc/wmYHP8JmBz/CZgc/wmYHP8JmBz/AAAAAAAAAAAAAAAA////////////////F5sr/w28LP8w10j9KL08/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////xebK/8UvS7/HKsv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8Xmyv/F5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////8AAAAAF5sr/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgv/AAID/wACA/8AAgP/AAIAAwACAAMAAgADAAIAAwACAAMAAgADAAIAAwACAAMAAgP/AAID/wACA/8AAgv/AAP//wAA="],
            ,
            ["Открыть папку для экспорта закладок", "reveal", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAABAAAAAWAAAAFQAAABQAAAAUAAAAEwAAABIAAAASAAAAEQAAABAAAAAPAAAADwAAAA4AAAALAAAAAwAAAAAAAAAHAAAALAAAAFUAAABjAAAAYgAAAGEAAABgAAAAYAAAAF0AAABcAAAAWwAAAFsAAABYAAAAVwAAAFYAAABJAAAAKAAAAAcAAAAXCgoKbomJid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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALi4uAR0dHQEREREEEhISBRAQEAMaGhoCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAB/wACB/8AA///AAP//wAA="],
            ["Экспорт закладок в HTML без запроса", "silentExport", "data:image/x-icon;base64,AAABAAEAEhIAAAEAIACABQAAFgAAACgAAAASAAAAJAAAAAEAIAAAAAAAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAHAAAAAwAAAAAAAAANAAAAMwAAAEsAAABOAAAATgAAAE4AAABOAAAATgAAAE4AAABOAAAATgAAAE4AAABOAAAATgAAAE8AAABKAAAAMQAAAAwAAAAuLCwsl2tra89nZ2fNZ2dnz2dnZ89nZ2fPZ2dnz2dnZ89nZ2fPZ2dnz2dnZ89nZ2fPZ2dnz2dnZ81sbGzPKCgokwAAACsAAABHy8vL/7+/v/+/v7//v7+//729vf+/v7//v7+//7+/v/+/v7//v7+//76+vv++vr7/vr6+/7+/v/+/v7//ycnJ/wAAAEIKCgpQ0tLS/8PDw//Dw8P/wsLC/+fn5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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//8AAgABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAwACD/8AA///AAP//wAA="]
        ])
            if (data) {
                var menuitem = popup.appendChild(document.createElement("menuitem"));
                menuitem.className = "menuitem-iconic";
                keys.forEach((key, ind) => menuitem.setAttribute(key, data[ind]));
            } else
                popup.appendChild(document.createElement("menuseparator"));
        delete this.popup;
        return this.popup = self.appendChild(popup);
    },
    get BookmarkHTMLUtils() {
        delete this.BookmarkHTMLUtils;
        Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm", this);
        return this.BookmarkHTMLUtils;
    },
    pref: "CB.exportsBookmarksToHTMLFile.path",
    get path() {
        return Services.prefs.getStringPref(this.pref, null);
    },
    pick(title, modeOpen) {
        var fp = makeFilePicker();
        fp.init(window, title, modeOpen ? fp.modeOpen : fp.modeGetFolder);
        modeOpen && fp.appendFilters(fp.filterHTML);
        var {path} = this;
        if (path) fp.displayDirectory = FileUtils.File(path);
        return new Promise(resolve => fp.open(
            res => resolve(res == fp.returnOK && fp.file)
        ));
    },
    async import() {
        var file = await this.pick("Выберите HTML-файл для импорта закладок", true);
        file && this.BookmarkHTMLUtils.importFromFile(file.path).then(null, alert);
    },
    async export(justSetPath) {
        var dir = await this.pick("Укажите папку для экспорта закладок!");
        if (!dir) return;
        dir.path != this.path && Services.prefs.setStringPref(this.pref, dir.path);
        justSetPath || this.silentExport(dir);
    },
    silentExport(dir) {
        if (!dir && !(dir = this.checkPath(this.path))) return;
        dir.append("bookmarks-" + new Date().toLocaleDateString("mn") + ".html");
        this.BookmarkHTMLUtils.exportToFile(dir.path)
            .then(() => this.notify(dir.path), alert);
    },
    ns: "Папка для экспорта не установлена.\n\nУстановить папку?",
    nf: path => `Папка для экспорта не найдена.\n${path}\n\nВыбрать другую?`,
    checkPath(path, justSetPath) {
        if (!path)
            return void(confirm(this.ns) && this.export(justSetPath));
        var dir = FileUtils.File(path);
        if (dir.exists() && dir.isDirectory()) return dir;
        confirm(this.nf(path)) && this.export(justSetPath);
    },
    reveal() {
        var dir = this.checkPath(this.path, true);
        dir && dir.reveal();
    },
    get notify() {
        var as = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
        var func = path => setTimeout(as.closeAlert, 3500, as.showAlertNotification(
            self.image, self.label, "Экспортировал закладки как HTML в " + path
        ));
        delete this.notify; return this.notify = func;
    }
});

Отсутствует

 

№1260028-05-2018 13:49:42

Garalf
Участник
 
Группа: Members
Зарегистрирован: 19-09-2017
Сообщений: 315
UA: Firefox 60.0

Re: Custom Buttons

Dumby
Спасибо!

Блин! И ещще одну кнопку упустил...
Dumby если будет время.... Экспорт в HTML файл в контекстном меню закладок
Удобная вещь. Тут каждую папку закладок отдельно копировать можно.

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

Выделить код

Код:

/*Initialization Code*/
//-------------------- Экспорт в HTML файл в контекстном меню закладок
//Источник - https://github.com/ardiman/userChrome.js/blob/master/exporthtmlfolder/ExportHTMLFolder.uc.xul
 (function () { 

 function ImageConverter(imageURL) {
       this.imageURL = imageURL;
       this.channel = Services.io.newChannel(imageURL, null, null);
       this.channel.asyncOpen(this, null);
}
 ImageConverter.prototype = {
       imageURL : "",
       channel : null,
       bytes : [],
       stream : null,
       Database64 : null,
       iscompleted : false,
       QueryInterface : function (iid) {
              if (!iid.equals(Components.interfaces.nsISupports) &&
                  !iid.equals(Components.interfaces.nsIRequestObserver) &&
                  !iid.equals(Components.interfaces.nsIStreamListener)) {
                  throw Components.results.NS_ERROR_NO_INTERFACE;
               }
               return this;
        },

        onStartRequest : function (aRequest, aContext) {
             this.stream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
             this.iscompleted = false;
         },

       onStopRequest : function (aRequest, aContext, aStatusCode) {
             this.Database64 = 'data:' + this.channel.contentType + ';base64,' + btoa(String.fromCharCode.apply(null, this.bytes));
             this.iscompleted = true;
         },

             onDataAvailable : function (aRequest, aContext, aInputStream, aOffset, aCount) {
             this.stream.setInputStream(aInputStream);
             var chunk = this.stream.readByteArray(aCount);
             this.bytes = this.bytes.concat(chunk);
          }
};
 var ExportHTMLFolder = {
      
        escapeHTML: function(str) {
             return str.replace(/[&"<>]/g, function (m) ({ "&": "&amp;", '"': "&quot", "<": "&lt;", ">": "&gt;" })[m]);
          },
          
        onMenuItemCommand: function(event) {
             var bookmarkService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService);
             var historyService = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
             var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
             var MPMenu = PlacesUtils.getString("BookmarksMenuFolderTitle");
             var NodeID = document.popupNode._placesNode || document.popupNode.parentNode.selectedNode;
             fp.init(window, PlacesUIUtils.getString("EnterExport"),Ci.nsIFilePicker.modeSave);
             fp.appendFilters(Ci.nsIFilePicker.filterHTML);
             fp.defaultString = NodeID.title+".html";

             fp.open(res => {
                   if (res == fp.returnCancel || !fp.file) return;
                   var file = fp.file;
                   var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                                 .createInstance(Components.interfaces.nsIFileOutputStream);
                   var charset = "UTF-8";
                   foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0);
                   var os = Components.classes["@mozilla.org/intl/converter-output-stream;1"]
                                   .createInstance(Components.interfaces.nsIConverterOutputStream);
                   os.init(foStream, charset, 0, 0x0000);
                   var nbTab = 5;
                   var data = '<!DOCTYPE NETSCAPE-Bookmark-file-1>\n';
                       data = data + '<!-- This is an automatically generated file.\n';
                       data = data + '\tIt will be read and overwritten.\n';
                       data = data + '\tDO NOT EDIT! -->\n';
                       data = data + '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">\n';
                       data = data + '<TITLE>Bookmarks</TITLE>\n';
                       data = data + '<H1>'+ExportHTMLFolder.escapeHTML(MPMenu)+'</H1>\n';
                       data = data + '\n';
                       data = data + '<DL><p>\n';
                   os.writeString(data);
                   var options = historyService.getNewQueryOptions();
                   var query = historyService.getNewQuery();
                   if( NodeID.type != 0 )
                      {
                        query.setFolders([NodeID.itemId], 1);
                        var result = historyService.executeQuery(query, options);
                        node = result.root;
                       }
                   else
                       {
                        query.setFolders([NodeID.parent.itemId], 1);
                        var result = historyService.executeQuery(query, options);
                        var rootNode = result.root;
                        rootNode.containerOpen = true;
                        inc = 0;
                        var node = rootNode.getChild(inc);
                        while(( inc < rootNode.childCount )&&( node.itemId != NodeID.itemId )) {
                            inc++;
                            var node = rootNode.getChild(inc);
                              }
                        rootNode.containerOpen = false;
                         }
                        this.ecrireUnMP( os, node, nbTab );
                        data = '</DL></p>\n';
                        os.writeString(data);
                        os.close();
                 });
          },
          
          ecrireUnMP: function( flux, elem, nbTab ) {
             var resultTypes = Ci.nsINavHistoryResultNode;
             if( elem.type == resultTypes.RESULT_TYPE_SEPARATOR ) {
                 var chaine = new Array(nbTab).join(' ') + "<HR>\n";
                 flux.writeString(chaine);
             }
             else if( elem.type == resultTypes.RESULT_TYPE_URI ) {
                 var Description= PlacesUIUtils.getItemDescription(elem.itemId);
                 var chaine = new Array(nbTab).join(' ') + '<DT><A HREF="' + this.escapeHTML(elem.uri);
                 if ( elem.icon.indexOf('moz-anno:favicon:http') >= 0 )
                 {
                       if ( elem.icon.indexOf('http://www.mozilla.org/2005/made-up-favicon/') < 0 ){
                                  chaine = chaine + '" ICON_URI="' + elem.icon.slice(elem.icon.indexOf('moz-anno:favicon:http') + 'moz-anno:favicon:'.length);
                        }
                       var Image = new ImageConverter( elem.icon.slice(elem.icon.indexOf('moz-anno:favicon:http')) );
                       var thread = Cc['@mozilla.org/thread-manager;1'].getService().mainThread;
                       while ( !Image.iscompleted ) {
                       thread.processNextEvent(true);
                       }
                        chaine = chaine + '" ICON="' + Image.Database64;
                  }
                  else if ( elem.icon.indexOf('moz-anno:favicon:data:image') >= 0 )
                        {
                        chaine = chaine + '" ICON="' +elem.icon.slice(elem.icon.indexOf('data:image'));
                        }
                        var chaine = chaine + '">' + this.escapeHTML(elem.title) + '</A>\n' + new Array(nbTab).join(' ') + '<DD>' + this.escapeHTML(Description) + '\n';
                        flux.writeString(chaine);
                         }
                  else if(( elem.type == resultTypes.RESULT_TYPE_FOLDER )||( elem.type == resultTypes.RESULT_TYPE_FOLDER_SHORTCUT )) {
                        var bookmarkService = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService);
                        var historyService = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
                        var Description= PlacesUIUtils.getItemDescription(elem.itemId);
                        this.escapeHTML(elem.title) + '</H3>\n';
                        var chaine = new Array(nbTab).join(' ') + '<DT><H3>' + this.escapeHTML(elem.title) + '</H3>\n';
                        var chaine = chaine + new Array(nbTab).join(' ') + '<DD>' + this.escapeHTML(Description) + '\n';
                        chaine = chaine + new Array(nbTab).join(' ') + '<DL><p>\n';
                        flux.writeString(chaine);
                        nbTab = nbTab + 4;
                        var options = historyService.getNewQueryOptions();
                        var query = historyService.getNewQuery();
                        query.setFolders([elem.itemId], 1);
                        var result = historyService.executeQuery(query, options);
                        var rootNode = result.root;
                        rootNode.containerOpen = true;
                        for (var inc = 0; inc < rootNode.childCount; inc ++) {
                              var node = rootNode.getChild(inc);
                              this.ecrireUnMP( flux, node, nbTab );
                         }
                         rootNode.containerOpen = false;
                         nbTab = nbTab - 4;
                         chaine = new Array(nbTab).join(' ') + '</DL></p>\n';
                         flux.writeString(chaine);
                   }
          },

          init: function()
           {
              var contextMenu = document.getElementById("placesContext");
              if (contextMenu) contextMenu.addEventListener("popupshowing", this.ExportHTMLFolderShowHideItem, false);
           },
          ExportHTMLFolderShowHideItem: function(event)
            {
              var show = document.getElementById("placesContext_ExportHTMLFolder");
              show.hidden = (document.popupNode.localName == "menuseparator")||( document.popupNode.className == "openintabs-menuitem");
              document.getElementById("placesContext_ExportHTMLFolderSep").hidden = show.hidden;
            },
};

       window.addEventListener("load", function load(event) {
       window.removeEventListener("load", load, false); //remove listener, no longer needed
       ExportHTMLFolder.init();
}, false);


  if ( document.getElementById("placesContext_ExportHTMLFolder") ) return; 

   
    var contextMenu = document.getElementById("placesContext");
    var copyBothMenuItem = document.createElement("menuitem"); 
    copyBothMenuItem.id = "placesContext_ExportHTMLFolder";
    copyBothMenuItem.setAttribute("label", "Экспорт в HTML");
    copyBothMenuItem.setAttribute("selection", "any");
    copyBothMenuItem.setAttribute("closemenu", "single");
    copyBothMenuItem.addEventListener("command", function () { ExportHTMLFolder.onMenuItemCommand(event); });
    contextMenu.insertBefore(copyBothMenuItem, document.getElementById("placesContext_newSeparator") );
    var SMenuItem = document.createElement("menuseparator"); 
    SMenuItem.id = "placesContext_ExportHTMLFolderSep";
    contextMenu.insertBefore(SMenuItem, document.getElementById("placesContext_ExportHTMLFolder") );
})();

Отредактировано Garalf (28-05-2018 19:04:10)

Отсутствует

 

Board footer

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