VK posts filter

Скрывает рекламные и политические посты в полной и мобильной версии соц. сети VK.COM. Высокое быстродействие в сравнении с аналогичными скриптами.

Version au 22/10/2016. Voir la dernière version.

Vous devrez installer une extension telle que Tampermonkey, Greasemonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Violentmonkey pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey ou Userscripts pour installer ce script.

Vous devrez installer une extension telle que Tampermonkey pour installer ce script.

Vous devrez installer une extension de gestionnaire de script utilisateur pour installer ce script.

(J'ai déjà un gestionnaire de scripts utilisateur, laissez-moi l'installer !)

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension telle que Stylus pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

Vous devrez installer une extension du gestionnaire de style pour utilisateur pour installer ce style.

(J'ai déjà un gestionnaire de style utilisateur, laissez-moi l'installer!)

// ==UserScript==
// @name            VK posts filter
// @name:en         VK posts filter
// @namespace       FIX
// @version         1.1.2
// @description     Скрывает рекламные и политические посты в полной и мобильной версии соц. сети VK.COM. Высокое быстродействие в сравнении с аналогичными скриптами.
// @description:en  Hide ad and political posts from vk.com in desktop and mobile versions. High Speed.
// @copyright       2016, raletag
// @author          raletag
// @supportURL      http://greasyfork.org/scripts/23100/feedback
// @include         *://vk.com/*
// @exclude         *://vk.com/notifier.php*
// @exclude         *://vk.com/*widget*.php*
// @include         *://m.vk.com/*
// @grant           none
// @run-at          document-end
// ==/UserScript==

(function() {
    'use strict';
    var showheader = true, // true - оставлять заголовок поста, false - полностью скрывать пост
        a = Date.now(),
        ads = 'побед(а|у) (в сражении|над боссом)|я (повысил|получил)(|а)(| новый) уровен|я тебя обогнал|вступай(|те) в|расска(зать|жите|зывай) дру(зьям|гу) про запись|дела(й|йте|ете|ть) репост|добав(ь|те|ляем|ляй) (активн(ого|ых))|(пиар(|ся|ьтесь) (тут|здесь))|подпи(шись|саться|сывайся|шитесь) на|активно добавля(й|ем)|(быть|стать|будьте|станьте) (подписчиком|участником)|уровень в игре|получить бесплатно|зач(е|ё)тны(е|й) кореш(|а)|победител(ь|я|и) розыгрыш|победил(|а) босс|я одержал(|а) побед|внимание розыгрыш|добав(ь|ьте|ляйтесь|лю|ляю|ляемся|ить) (в дру|его|её|их|все|за|через)|(за|делавшему|делай|конкурс) репост|при(ми|мите|нять|нимайте) участие|результат(|ы) конкурс|(прош(ел|ла)|меня|достиг(|ла)) (| [0-9]{1,})уров|зака(жи|жите|зывай|зывайте) по акци|я выполнил(|а) задани|успей(|те) (вступить|подписаться)|смотреть ответ|читать продолжение|только для участников сообществ|науч(у|итесь) бесплатн|пере(йди|йдите|ходи|ходим|ходите) по ссылк|успей(|те) добав|ссылка на рег|закажи(|те) сейчас|ответ на новую политику|(й|и|е|м|т) промокод|получи(|те) скид',
        urlads = 'vk\.com\/(app|top_cards|fotomimi|flower_cards|megatest|beauty_cards|fotomagic_su|we_love_cards|denegnoe_derevo|skanograf|pr0werka|musicwars|love1v|vkvoprosnik)|(clickerwars|schoolclicker)\.com\/vk|denezhnojederevo\.ru|ref=|partner=|act=invite&group_id=',
        politiс = 'выборы в|правительств|националист|оппозици|ополчен|петици|митинг|парламент|фальсификац|госдум|арест|террорист|теракт|антигосударств|#политика|#выборы',
        regexp = new RegExp('(' + ads + '|' + urlads + '|' + politiс +')', 'mi'),
        MutationObserver = window.MutationObserver,
        ismobile = (window.location.hostname === 'm.vk.com'),
        rbody = (ismobile?'.wi_body':'.wall_text'),
        rlnk = (ismobile?'a.medias_link[href*="vk.com/app"]':'a.lnk[href*="vk.com/app"]'),
        radatt = (ismobile?'data-ad-view':'data-ad'),
        rqsa = (ismobile?'div[id*="wall"].wall_item:not([vpf])':'div[data-post-id].post:not([vpf])'),
        rwc = (ismobile?'wall_item':'post'),
        filter = function  (e) {
            e.setAttribute('vpf', '1');
            var text = e.querySelector(rbody);
            if (e.querySelector(rlnk)  || e.getAttribute(radatt) || (text && (regexp.test(text.textContent)))) {
                if (showheader === true) {
                    if (ismobile) {
                        text.innerHTML = '';
                    } else {
                        e.querySelector('.post_header').classList.add('post_header_fix');
                        e.querySelector('.post_content').innerHTML = '';
                    }
                } else {
                    e.innerHTML = '';
                }
            }
        };

    if (showheader === true && !ismobile) {
        var style = document.createElement("style");
        style.innerHTML='.post_header_fix {padding: 15px 20px 15px!important;}';
        (document.head||document.body||document.documentElement||document).appendChild(style);
    }

    if (!/^\/wall(.*)_/.test(window.location.pathname)) {
        for (var links = document.body.querySelectorAll(rqsa), i = links.length - 1; i >= 0; --i) {
            filter (links[i]);
        }
    }
    if (MutationObserver) {
        new MutationObserver(function (ms) {
            if (document.body.querySelector('div.apps_options_bar') || /=wall/.test(window.location.search) || /^\/wall(.*)_/.test(window.location.pathname)) return;
            ms.forEach(function (m) {
                m.addedNodes.forEach(function (n) {
                    if (n.nodeType !== Node.ELEMENT_NODE) {
                        return;
                    }
                    if (n.id !== null && n.classList.contains(rwc) && !n.getAttribute('vpf')) {
                        filter (n);
                    } else {
                        for (var links = n.querySelectorAll(rqsa), i = links.length - 1; i >= 0; --i) {
                            filter (links[i]);
                        }
                    }
                });
            });
        }).observe(document.body, {childList:true, subtree:true});
    } else {
        document.body.addEventListener('DOMNodeInserted', function(e) {
            if (e.currentTarget) {
                for (var links = e.currentTarget.querySelectorAll(rqsa), i = links.length - 1; i >= 0; --i) {
                    filter (links[i]);
                }
            }
        }, false);
    }
    console.log('VK posts filter: ' + (Date.now() - a) + 'ms');
})();