通过`onmousedown`,`click` events

时间:2017-03-26 15:10:56

标签: javascript jquery google-chrome-extension yandex

基本上,当我在Yandex中a search时,我会得到类似的结果:

pic

然而,当我右键单击并复制链接时,我没有得到真正的链接,但是那个垃圾链接(在重定向到我想要的链接之前用作跟踪点击功能的中间链接) )。

我试图编写一个删除那些垃圾链接的脚本。这就是我尝试过的:

function decodeURL(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

function getRealLinks() {
    var classes = document.getElementsByClassName('organic typo typo_text_m typo_line_s'); // gets any search result

    var cleanLinks = new Array(); // we'll store any clean link to this array

    for (i = 0; i < classes.length; i++) {
        var html = classes[i].innerHTML; // we get part of the inner html of the selected search result
        var pattern = /(url=(.*?))(?=&amp;\w+=)/; // with this regex we'll match the url
        var match = pattern.exec(html); // attempt matching pattern
        cleanLinks.push(decodeURL(match[2])); // decode the url, then push the match to the array
    }

    console.log(cleanLinks);
}

function bindEventListeners() {
    var lis = document.getElementsByTagName('li'); // search results have `li` selector

    for (var i = 0; i < lis.length; i++) { // iterate every element
      (function(i) {
        lis[i].addEventListener('click', function() { // add a listener to the current element
          alert(this.dataset.cid); // each result has an id (by default between 0-9)
        }, false);
      })(i);
    }
}

bindEventListeners();

getRealLinks()给了我正确的链接,但我现在还不知道如何进步&#34;用干净的链接替换搜索结果的href

bindEventListeners()被调用,绑定将在搜索结果正文部分实现点击时触发的侦听器。获取点击的搜索结果的id对我来说很有用,只是为了让链接偏离我需要的链接。例如,用户点击索引为3的搜索结果,我会var search_3 = getRealLinks()[3]

如何在JavaScript中用干净的链接替换那些你可以看到的链接?

1 个答案:

答案 0 :(得分:2)

mousedown(最顶层的DOM对象)上附加window侦听器,并为addEventListener useCapture 参数指定true以拦截在从window到点击目标的捕获阶段开始时的事件。也就是说,我们的代码将在目标onmousedown之前运行。

// ==UserScript==
// @name     Defluff yandex links
// @include  *://yandex.*/*
// ==/UserScript==

window.addEventListener('mousedown', event => {
    const a = event.target.closest('a');
    if (a) {
        a.onmousedown = null;
    }
}, true);