search

Showing posts with label firefox. Show all posts
Showing posts with label firefox. Show all posts

Thursday, November 16, 2017

fedora: Install flashplayer in Firefox

I have flashplayer installed on my system from the official Adobe repository, but Firefox for some reason does not have flash plugin installed. You can check if your browser supports flash by navigating to this url

To make Firefox aware of flashplugin, try to create a symlink here:

cd http://isflashinstalled.com/ && ln -s /usr/lib64/flash-plugin/libflashplayer.so .

Friday, October 13, 2017

Firefox Quantum: No titlebar

In "old" Firefox times I used to use HTitle extension. It removes useless titlebar in Firefox in GNOME 3. However, the extension was discontinued. Firefox starting version 56 does not support Legacy extension and new solution is needed.

I wrote a small application which hides titlebar of the maximized windows. xnotitle is written in Go. By default, every second it checks for a new window which contains "Mozilla Firefox" in the title and applies special style to disable the title bar when the window is maximized.

xnotitle can be used to hide title bar for any application. Specify window title to hide with -name argument. You can also adjust how often xnotitle is going to check for new windows.

To start using application, clone the repository and build the project:

git clone git@github.com:jsnjack/xnotitle.git
make build
You should have go installed.

After xnotitle is compiled, start it automatically with the system by creating ~/.config/autostart/xnotitle.desktop file with the following content:

[Desktop Entry]
Type=Application
Name=xnotitle
Comment=xnotitle hides title bar of the specified windows
Exec=/home/jsn/go/src/github.com/jsnjack/xnotitle/xnotitle
Terminal=false

I recommend also installing Close Window Button extension to add Close window button (as titlebar is gone and all window control buttons too)

Sunday, November 15, 2015

firefox: Enable tracking protection for normal session

Firefox 42 includes very interesting feature - Tracking protection. By default it is active only in the Private mode. When the Firefox team presented a new video that described the usage of the Memory tab in the Developer toolbar, they show that the CNN website normally consumes about 40 Mb of memory and with Tracking protection on it consumes about 10 Mb. If you want to enable this feature not only for the private sessions, but also for the normal sessions, you can do that by typing about:config in the address bar and changing the value of the privacy.trackingprotection.enabled to true: There is also a really interesting setting privacy.trackingprotection.updateURL, which means, that, I believe, you can host your own tracking protection list (See shavar project, blocking list format is here). When Tracking protection has blocked some resources, it shows a shield icon near the address bar. If you open the Developer console (F12 or Ctrl+Shift+K) you can see what resources were blocked: Together with AdBlock extension it could be a nice way to improve your browsing expierence.

Friday, November 7, 2014

python: Precompile nunjucks files on change

Preface

I have been writing an Firefox extension for some time. It generates HTML content which depends on the context. When I started, I decided to do it with JavaScript:
var container = document.createElement("div");
document.getElementById("items-list").appendChild(container);

However, JavaScript quickly became messy. Another problem was that I didn't have HTML in front of me to create stylesheet.

I have used JavaScript template engine in one of my projects recently. It would be nice to do it in the Firefox extension. There will be at least two benefits: my JavaScript will be shorter and cleaner to read and I will be able to see HTML to easy write css.

I choose nunjucks template engine by Mozilla. It is fast, feature rich and copies Jinja2 syntax. To be honest, the last reason was the most important for me. I have developed several web applications in Django and Flask and really like django templates and jinja2 syntax.



Nunjucks easy integrates in the webpage. It is as simple as that:
1. Load script in you HTML:
<script src="nunjucks.js"></script>

2. Render template with context and append it to the page:
var rendered_html = nunjucks.render('templates/index.html', { foo: 'bar' });
document.getElementById("container").innerHTML = rendered_html;

I tried the same approach in the Firefox extension. I needed to append HTML in the toggle button popup container. So I loaded nunjucks.js inside popup (it is called panel in the Firefox) by passing it to contentScriptFile option.

Problem

Unfortunately, nunjucks wasn't able to find template I wanted it to render. As far as I know It makes Ajax request to your server (what server in case of Firefox extension, ha?) to retrieve HTML file and then renders it. Nunjucks also supports precompiled templates (which indeed it renders much faster). Precompiled templates are preferable in the production and are represented as JavaScript files. So my idea was to precompile templates and pass these JavaScript files with contentScriptFile option. In the nunjucks.render function it looks for the array instance with the same name as path to the Ajax request('templates/index.html' in the example above) and if it exists it starts to render it without downloading an html template. Exactly what we need!

Templates are compiled into JavaScript files by precompile bash script. It is inside bin folder of the nunjucks git repository. Lets clone the repository:
cd /home/jsn/app/git_projects/
git clone https://github.com/mozilla/nunjucks.git

We also need to install some dependencies. Firstly, we install nodejs package and nodejs package manager:
sudo yum install nodejs npm

Then two nodejs packages:
npm install chokidar optimist

No we are able to compile template into JavaScript file with command:
/home/jsn/app/git_projects/nunjucks/bin/precompile path_to_html >> path_to_js

There is a problem with that command: it looks ugly because it demands absolute paths to the HTML and JavaScript files. If you run it and open compiled file you will see that precompile script used absolute path_to_template to identify template. That is not what we need as we are going to use just filename as identifier ("index.html"). To fix last problem we can pass --name to the precompile command:
/home/jsn/app/git_projects/nunjucks/bin/precompile --name index.html path_to_the_index.html >> path_to_the_index.js

Now we have the command which we are supposed to execute on every HTML file change. It would be nice to automate that step. So we need a script which will check every template in our templates folder and if a file was changed it would compile the file.

Solution

We are going to write that script in Python. First of all we need list of all files inside template folder. We will use listdir method of os package:
file_list = os.listdir(templates_dir)

File modification time we can check with os.getmtime() method. We will create global dictionary FILES. The keys of that dictionary will be file names and values will be last modification time. All we need to do is to fill that dictionary on the script start up and run precompile command if last modification time was changed.
FILES = {}
TIMER = 1

COLOUR_END = '\033[0m'
COLOUR_GREEN = '\033[92m'
COLOUR_BLUE = '\033[94m'


def check_templates(templates_dir=TEMPLATES_DIR):
    file_list = os.listdir(templates_dir)
    for item in file_list:
        if item.split(".")[-1] == "html":
            modified = os.path.getmtime(templates_dir + "/" + item)
            if item in FILES:
                if FILES[item] != modified:
                    FILES[item] = modified
                    precompile(templates_dir, item)
            else:
                print (COLOUR_BLUE + item + " is being watched" + COLOUR_END)
                FILES[item] = modified
                precompile(templates_dir, item)

We also filter files in our template directory by extension (as we are interested only in the html files). I use print function to inform myself when script finds new file in directory. Note, that these lines will be blue. It will make that event more noticeable.

We will check files for changes every second (TIMER variable):
if __name__ == '__main__':
    while True:
        check_templates()
        sleep(TIMER)

We can ask Python to execute for us any command we would normally execute in bash. Call method of the subprocess package helps to do it.
def precompile(tempates_dir, filename):
    compiled_filename = filename.replace("html", "js")
    path_to_js = tempates_dir + "/" + compiled_filename
    path_to_html = tempates_dir + "/" + filename
    if os.path.exists(path_to_js):
        call("rm -f " + path_to_js, shell=True)
    command = NUNJUCKS_REPO + "/bin/precompile --name " + filename + " " + path_to_html
    command = command + " >> " + path_to_js
    call(command, shell=True)
    print(COLOUR_GREEN + datetime.now().strftime("%X" + " " + filename + " ...OK") + COLOUR_END)

By default if compiled JavaScript exists, precompile command will add newly compiled data to it, so we have to check if compiled file exists with os.path.exists() method and remove it with bash rm -f command. NUNJUCKS_REPO is the path to the cloned nunjucks repository.

There is still a thing we can improve in the script. I will store that script in the project repository and I would like to use it on different machines. So hard coded template and nunjucks directory paths is not the option. I would like to set them as commands arguments to our script or maybe I will set these paths as environment variables. Anyway, full version of the script is below:
#!/usr/bin/python

# This script will monitor templates folder and automatically compile nunjucks html templates on change

import os
import sys
from datetime import datetime
from subprocess import call
from time import sleep

try:
    NUNJUCKS_REPO = sys.argv[1]
except IndexError:
    NUNJUCKS_REPO = os.getenv("NUNJUCKS_REPO")
try:
    TEMPLATES_DIR = sys.argv[2]
except IndexError:
    TEMPLATES_DIR = os.getenv("TEMPLATES_DIR")

FILES = {}
TIMER = 1

COLOUR_END = '\033[0m'
COLOUR_GREEN = '\033[92m'
COLOUR_BLUE = '\033[94m'


def check_templates(templates_dir=TEMPLATES_DIR):
    file_list = os.listdir(templates_dir)
    for item in file_list:
        if item.split(".")[-1] == "html":
            modified = os.path.getmtime(templates_dir + "/" + item)
            if item in FILES:
                if FILES[item] != modified:
                    FILES[item] = modified
                    precompile(templates_dir, item)
            else:
                print (COLOUR_BLUE + item + " is being watched" + COLOUR_END)
                FILES[item] = modified
                precompile(templates_dir, item)


def precompile(tempates_dir, filename):
    compiled_filename = filename.replace("html", "js")
    path_to_js = tempates_dir + "/" + compiled_filename
    path_to_html = tempates_dir + "/" + filename
    if os.path.exists(path_to_js):
        call("rm -f " + path_to_js, shell=True)
    command = NUNJUCKS_REPO + "/bin/precompile --name " + filename + " " + path_to_html
    command = command + " >> " + path_to_js
    call(command, shell=True)
    print(COLOUR_GREEN + datetime.now().strftime("%X" + " " + filename + " ...OK") + COLOUR_END)


if __name__ == '__main__':
    while True:
        check_templates()
        sleep(TIMER)




As we use only precompiled JavaScript templates we can switch to nunjucks-slim.js. Slim version is smaller and works only with precompiled templates.

If you have any suggestions or questions, please let me know in the comments.

Saturday, April 13, 2013

firefox: Подтверждение о закрытии при активной закачке

Для появления подтверждения о закрытии браузера при активных закачках необходимо открыть страницу скрытых настроек firefox. Для этого в строке ввода адреса вводим:
about:config

Находим пункт
browser.download.manager.quitBehavior

И присваиваем ему значение 2 (по умолчанию должно стоять 0).

Готово. Очень помогает, если забываешь о том, что есть активная загрузка с файлообменника.

Sunday, March 31, 2013

fedora 18: Adobe Flash Player 11.3

Столкнулся с проблемой, что некоторые сайты (например, livemocha) для работы требуют версию Adobe Flash Player 11.3 и выше. Последняя версия для linux - это 11.2. И к сожалению, для Linux Adobe больше не будет выпускать Flash Player новой версии. Будут выходить только обновления безопасности.

Для пользователей linux есть только одна возможность использовать flash player последних версий. Для этого надо установить браузер Chrome от Google (не Chronium). Он имеет встроенный Flash Player последней версии.

В репозитории fedora браузер не был обнаружен, поэтому установим его с сайта производителя . Нажимаем Download Chrome и выбираем нужную версию.

Программа занимает 50.8 Мб (rpm, 32bit). У меня почему-то она сохранилась под именем ".rpm". Если имя файла или папки начинается с точки, то linux считает их скрытыми и не показывает в файл-менеджере, если отдельно его об этом не попросить:

Переименуйте файл так, чтообы он имел вид имя.расширение. Простым двойным кликом установить не получится, так как потребуется какой-то сертификат, которого нету.

Запускает терминал, и выполняем команду из папки с установщиком chrome:
su -c'yum install chrome.rpm'

Chrome установлен и Livemocha работает:

Thursday, March 21, 2013

firefox: Как отключить встроенный pdf-просмотрщик

В 19 версии появился встроенный pdf-просмотрщик. У меня с ним проблемы как в Windows так и в Linux. В Windows у меня он вызывал BSOD при просмотре одного документа (может и сам документ плохой был, но не так же на него реагировать!). В Linux он работает ужасно медленно...

Итак, чтобы отключить его надо набрать в строке ввода web-адреса
about:config

Нажать Enter, пообещать быть осторожным. Изменить значение пункта меню:
pdfjs.disabled

на
true