Андрей Смирнов
Время чтения: ~12 мин.
Просмотров: 8

Аддон Tampermonkey для популярных браузеров

Tampermonkey — расширение для браузера, с помощью которого можно управлять пользовательскими скриптами для различных сайтов. Данное расширение является чрезвычайно популярным, потому что оно позволяет автоматизировать повседневные задачи, улучшать определенные сайты, меняя их внешний вид, добавляя новые функции или скрывая нежелательные вещи.

Установка расширения Tampermonkey 

Ссылки для скачивания можно найти на официальном сайте расширения. Расширение существует для ChromeMicrosoft Edge, SafariOpera Next и Firefox

Как пользоваться Tampermonkey

После установки расширения вам необходимо найти пользовательский скрипт с необходимыми вам функциями для нужного сайта или написать собственный скрипт.

Давайте рассмотрим процесс написания собственного скрипта для автоматизации какого-нибудь действия.

Есть футбольный онлайн менеджер Живи Футболом. Один из способов заработать там виртуальную валюту для своего клуба – это заключать контракты на показ рекламы во время домашних матчей. На бесплатном аккаунте необходимо заходить раз в 15 минут на страницу и проверять возможность заключить более выгодный контракт. Если есть возможность заключить новый контракт, то надо нажать на зеленую стрелочку.

2019-06-18_23-17-22.png

Давайте автоматизируем данное действие с помощью Tampermonkey и нашего скрипта в браузере Google Chrome.

Для создания нового скрипта необходимо нажать на значок расширения, а потом выбрать «Создать новый скрипт…».

2019-06-18_23-24-47.png

В открывшемся окошке мы будем писать наш скрипт. Сначала заполняем начальные параметры:

 // ==UserScript==  // @name         Живи Футболом! Рекламные контракты…  // @namespace    https://pogrommist.ru/  // @version      0.1  // @description  Живи Футболом! Подписывай лучшие рекламные контракты!  // @author       pogrommist.ru  // @match        *://soccerlife.ru/base.php?mode=adverts  // @grant        GM_setValue  // @grant        GM_getValue  // ==/UserScript==

Дальше напишем код, который будет запрашивать разрешение на вывод уведомлений в браузере.

document.addEventListener('DOMContentLoaded', function () {   if (!Notification) {     alert('Оповещения недоступны в вашем браузере. Используйте Chrome!');     return;   }    if (Notification.permission !== 'granted') {     Notification.requestPermission();} });

Наш скрипт запускается только на странице *://soccerlife.ru/base.php?mode=adverts, поэтому если мы сейчас зайдем на главную страницу, то ничего не увидим нового. А если зайдем на страницу с рекламными контрактами, то браузер запросит у нас разрешение на показ уведомлений.

2019-06-18_23-35-36.png

Теперь напишем функцию, которая будет показывать нам уведомления:

function notifyMe(text) {    if (Notification.permission !== 'granted'){      Notification.requestPermission();}    else {      var notification = new Notification('Активное предложение', {        icon: 'https://img.icons8.com/color/48/000000/money-bag.png',        body: text,      });  }  }

Дальше опишем логику наших действий. Нам необходимо на странице найти стрелочки и посмотреть активна хотя бы одна из них или нет. Если хотя бы одна стрелочка активна, значит есть возможность заключить контракт.

Если посмотреть исходный код страницы, то видно, что у активных и неактивных стрелочек есть определенный class. Его мы и будем использовать.

function check() {      var div_up = document.getElementById("billboard_arrow_up").className;      var div_down = document.getElementById("billboard_arrow_down").className;      var div_left = document.getElementById("billboard_arrow_left").className;      var div_right = document.getElementById("billboard_arrow_right").className;      if (div_up=="billboard_arrow billboard_hidden" && div_down=="billboard_arrow billboard_hidden" &&          div_left=="billboard_arrow billboard_hidden" && div_right=="billboard_arrow billboard_hidden") {          //notifyMe("Ничего интересного. Ждем следующее предложение…");      }      else {notifyMe("Можно заключить контракт!");            document.getElementById("billboard_arrow_left").click();            document.getElementById("billboard_arrow_up").click();            document.getElementById("billboard_arrow_right").click();            document.getElementById("billboard_arrow_down").click();            notifyMe("Заключили контракт!");           }  }

Остается только написать периодический вызов функции для проверки доступности активных предложений:

(function() {     'use strict';      var div = document.getElementById("billboard_offer_cost");      setInterval(function(){      check();      location.reload();},                  300000);  })();

Теперь пока открыта вкладка с рекламными предложениями наш скрипт каждые 5 минут будет проверять возможность заключить контракт, перезагружая страницу для обновления информации.

Вот так мы автоматизировали один из процессов в онлайн игре.

Enhance your web browser’s capabilities with these free extensions

221 221 people found this article helpful

Greasemonkey and Tampermonkey are free extensions that significantly enhance your web browser’s capabilities. These powerful add-ons let you choose from thousands of unique user scripts that modify the behavior or appearance of a web page. Written by third-party developers in the JavaScript programming language, the functionality of these scripts range from downloading entire Facebook and Instagram albums in one click to completely revamping Pandora’s look and feel. Install either Greasemonkey or Tampermonkey, depending on your browser, to serve as your user script manager. After you have a script manager extension installed, you can search for extensions or try out some of the ones listed below.

Installing and Using Greasemonkey

GettyImages-9598530521-d2d1beb88122428eab171b8294990b3d.jpg
vladwel / Getty Images

It’s important to note that Greasemonkey is only available for Firefox. To get started, open your Firefox browser and navigate to the Greasemonkey download page, found on Mozilla’s add-ons website. Once there, click on the green and white button labeled Add to Firefox to downloadGreasemonkey, which usually takes a few seconds. When a pop-out dialog appears in the upper left corner of the browser window, click on the Install button. Once the installation is complete, you are prompted to restart Firefox.

After Firefox restarts, a new button in the form of a smiling monkey has been added to your browser’s address bar. Clicking on the smiling monkey button allows you to enable or disable the Greasemonkey extension. Selecting the down arrow accompanying the button lets you modify Greasemonkey’s settings and open Firefox’s User Scripts management interface.

Installing and Using Tampermonkey

Unlike Greasemonkey, which only runs on Firefox, Tampermonkey is available for a wide range of web browsers. What is similar to Greasemonkey, however, is that the Tampermonkey add-on is also managed through the menu associated with its address bar button. From here you toggle its functionality off and on, check for updates, create your own user script and open a dashboard where you can manage Tampermonkey’s settings as well as all the scripts that have been installed.

To install Tampermonkey on Chrome, Microsoft Edge, Firefox, Safari, and Opera Next, visit the extension’s official website and follow the instructions specific to your browser.

Finding More User Scripts

The number of user scripts available as well as their seemingly endless purposes grows by the day. When you are ready to start searching for scripts, the following sites are your best starting points. Not every script works across all browsers, so be sure to check the corresponding description/notes before installation. 

  • Greasy Fork: With a rapidly growing compendium of over 10,000 scripts, a well-maintained and easy-to-use interface, and active forum, Greasy Fork is a terrific source for user scripts. There’s even a script available titled Greasy Fork Bull**** Filter that makes searching the site even easier by hiding all scripts for games and social networks, as well as those using non-English characters in their Greasy Fork descriptions.
  • OpenUserJS: Another user-friendly repository with a constantly expanding selection, OpenUserJS offers a wide range of scripts.
  • Userscripts.org (mirror): At one time, Userscripts.org was the only place to go if you wanted to find the best scripts. Unfortunately, it was taken offline a while back and is now available as a mirrored site on a different domain. While you’ll find thousands of scripts on this mirror site, you’ll also find that many of them are not safe. Use added discretion when downloading from the Userscripts.org mirror.

The Top User Scripts

With such a large number of scripts available, it’s hard to know which are the best and safest ones to use. Here are some of the best scripts, listed in alphabetical order. 

User scripts are not vetted in the same fashion that most browser extensions are, so you should use them at your own risk. The scripts featured here each have a significant user base and have proven to be relatively safe. With that said, there are no guarantees when it comes to their overall safety.

Amazon Smile Redirect

Whenever you shop on Amazon Smile as opposed to the main site, a portion of your eligible purchase price is donated to your favorite nonprofit charity. This script ensures that you’re always redirected to smile.amazon.com each time you shop on Amazon. 

Compatibility note: No known compatibility issues.

Anti-Adblock Killer

While many websites either recommend or force you to disable ad-blocking software such as Adblock Plus, this script can override that restriction in some cases and allow your ad blocker to function as expected.

Compatibility note: No known compatibility issues.

AntiAdware

A lot of free downloads are coupled with additional applications, extensions or settings modifications that you probably don’t want. This can include somewhat harmless additions such as a branded browser toolbar or a change to your home page but can also mean installing adware and other less-than-reputable software. This script does a good job of removing these unwanted items on some of the web’s most popular sites.

Compatibility note: No known compatibility issues.

Auto Close YouTube Ads

This configurable script automatically closes YouTube video ads after a time delay that you decide on. It also offers the ability to mute these advertisements as soon as they launch.

Compatibility note: No known compatibility issues.

Direct Links Out

Many websites display a warning and require user interaction when you click on a link that redirects to another site. This script disables that functionality on many well-known domains including Google, YouTube, Facebook, and Twitter.

Compatibility note: No known compatibility issues.

Feedly Filtering and Sorting

The Feedly Filtering and Sorting script adds some useful features such as advanced keyword matching, auto-load, filtering, and restricting to the popular news aggregation site.

Compatibility note: No known compatibility issues.

Google Hit Hider by Domain

Block certain websites or entire domains from appearing in your search engine results with this script. The title is a bit misleading, as it supports Bing, DuckDuckGo, Yahoo and some other search engines in addition to Google. 

Compatibility note: Works best with Chrome or Firefox.

Google Search Extra Buttons

This script adds some useful buttons to Google’s engine, including the ability to search for PDF documents and search for results only from user-specified time intervals including days, weeks, months, years, and hours.

Compatibility note: No known compatibility issues.

Instagram Reloaded

View and download full-size images and videos from Instagram simply by pressing a keyboard shortcut with this script.

Compatibility note: Works with all browsers, but the direct download feature only works with Chrome.

Linkify Plus Plus

This script allows you to convert text URLs and IP addresses found on a web page into actual links to their respective destinations.

Compatibility note: No known compatibility issues.

Manga Loader

If you’re a fan of the Japanese comic genre, this script comes in handy by displaying complete chapters on one page in an easy-to-read long strip format on many of the web’s most popular Manga sites.

Compatibility note: No known compatibility issues.

Mouseover Popup Image Viewer

This script displays full images and video clips when you hover your mouse cursor over the links that lead to these multimedia assets, avoiding the need to click on them. Many lesser-known image and video-hosting services are supported, along with popular sites like Facebook and YouTube.

Compatibility note: This script may not function as expected in browsers other than Chrome, Firefox or Opera.

Pinterest Without Registration

This script lets you browse image collections on Pinterest without having to create an account on the site, although it does not seem to work as expected on all pages.

Compatibility note: No known compatibility issues.

Remove Sponsored Posts

This script hides suggested posts and sponsored stories in your Facebook feed.

Compatibility note: No known compatibility issues.

Resize YT to Window Size

Modify the YouTube interface so that the most important component, the video itself, takes precedence in your browser’s viewing area with this script.

Compatibility note: No known compatibility issues.

Rotten Tomatoes Link on IMDb

A neat addition for movie buffs, this script adds a button that links to the Rotten Tomatoes movie description on every IMDb page, when applicable.

Compatibility note: No known compatibility issues.

Simple YouTube MP3 Button

This script adds a button that lets you download the audio behind almost any YouTube video in MP3 format, converting on-the-fly before the file is retrieved from the server.

Compatibility note: No known compatibility issues.

Read the YouTube to MP3 Guide for other ways of pulling this off.

SoundTake: SoundCloud Downloader

This script lets you download most songs from the popular audio streaming sites.

Compatibility note: Some compatibility issues exist with Firefox.

Translate.google Tooltip

Use this script to translate selected text on a web page to the language of your choice with just the alt key and your mouse cursor.

Compatibility note: No known compatibility issues.

Tumblr: Mass Post Features

This script significantly enhances Tumblr’s Mass Post Editor, adding over a dozen new abilities to the blogging site’s batch re-tagging/deletion tool.

Compatibility note: No known compatibility issues.

Wide GitHub

Programmers find this script useful. It resizes all GitHub repository pages for a better look and feel.

Compatibility note: No known compatibility issues.

YouTube Best Video Downloader 2

This YouTube download script lets you retrieve videos in a number of different formats via its conveniently placed drop-down menu.

Compatibility note: No known compatibility issues.

tampermonkey.png

Tampermonkey UserScript

Tampermonkey — это бесплатное расширение браузера и популярный менеджер UserScript пользовательских скриптов для браузеров Chrome, Microsoft Edge, Safari, Opera Next, и Firefox.  Расширение поддерживает такие функции, как простая установка скрипта, автоматические проверки обновлений, простой обзор скриптов, запущеных на вкладке, а также имеет встроенный редактор. Кроме того, есть хорошие шансы на то, что несовместимые скрипты будут нормально работать при использовании расширения.

Tampermonkey: настройка UserScript в браузере

  • легкий доступ к скриптам
  • легко конфигурируемая страница настроек
  • автоматическое обновление скриптов через определённые (настраиваемые) промежутки времени
  • использование встроенного редактора
  • Проверка синтаксиса пользовательского скрипта при помощи JSHint (!)

Что можно написать на пользовательских скриптах?

  1. Автоматическое размещение новостей в социальных сетях
  2. Автоматический репостинг сообщений из групп (но придётся постараться)
  3. Автоматическая отметка «Мне нравится»
  4. Много разных и интересных вещей 🙂

Что посмотреть о пользовательских скриптах?

  • Greasemonkey (пользовательские скрипты под Firefox)
  • Учимся писать userscript’ы
  • Зеркало старого http://userscripts.org/

Используемые источники:

  • https://pogrommist.ru/2019/06/chto-takoe-tampermonkey-i-kak-im-polzovatsja/
  • https://www.lifewire.com/top-greasemonkey-tampermonkey-user-scripts-4134335
  • http://htmllab.ru/tampermonkey/

Рейтинг автора
5
Подборку подготовил
Максим Уваров
Наш эксперт
Написано статей
171
Ссылка на основную публикацию
Похожие публикации