簡體   English   中英

通過onmousedown,click事件更改href鏈接

[英]Change `href`s links via `onmousedown`,`click` events

基本上,當我在Yandex中進行搜索時,會得到如下信息:

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()為我提供了正確的鏈接,但是我現在不知道如何“進行”以用干凈的鏈接替換搜索結果的href

所謂的bindEventListeners()綁定將在搜索結果主體部分實現點擊時觸發的偵聽器。 獲得單擊的搜索結果的id對我很有用,只是使鏈接偏離了我所需的鏈接。 例如,用戶單擊索引為3的搜索結果,我將執行var search_3 = getRealLinks()[3]

如何用JavaScript中的干凈鏈接替換那些您可以看到的鏈接?

在最頂部的DOM對象window上附加一個mousedown偵聽器,並為addEventListeneruseCapture參數指定true ,以在從window到click目標的捕獲階段的一開始就攔截事件。 也就是說,我們的代碼將在目標的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM