簡體   English   中英

運行某個鏈接,而無需單擊實際的鏈接按鈕

[英]Run a certain link without clicking the actual link button

我正在嘗試編寫一個腳本來替換當前的cookie,然后轉到網站中的鏈接,然后替換下一個cookie。 所有cookie都存儲在一個數組中。 到目前為止,我有以下代碼:

var i;
for(i=0;i<arr.length;i++){
    var cookie = arr[i];
    //setting the new cookie that was fetched from the array:
    document.cookie = 'cookieName='+cookie+'; path=/';
    //Now I need to run the <a href> which links to a relative path
    //I am currently in www.mydomain.com/page1/subpage1
    //And the href is to /page1/subpage2.I want the script to run this link every iteration
}

我需要運行/page/subpage2鏈接,而無需實際使用JS單擊它。

該鏈接實際上不會更改當前頁面,它是運行一些服務器端代碼的鏈接,但實際上您位於同一頁面www.mydomain.com/page1/subpage1 ,因此您不必重定向回page1/subpage1

這是一個簡單的網站,鏈接的元素上沒有id,它是一個表,其中的鏈接看起來像這樣:

<table>
<!--more rows here-->
<tr>                        
<td>                        
<a class='table-row' href='/page1/subpage2'> Click </a>
</td>
</tr>
<!--more rows here-->
</table>

使用forEach在數組內部循環。 將el關聯到cookie並更改array元素。 然后觸發具有不良href的a的點擊。

// never define variables inside the loop when possible
var cookie;
arr.forEach(function (el, ind) {
    cookie = el;
    arr[ind] = 'document.cookie = \"cookieName='+cookie+'; path=/;"';
    document.querySelector('a[href="mypath"]').triggerHandler('click');
});

您可以創建新的click事件並像下面的代碼中一樣分派它。

在此示例中,我們遍歷類table-row所有鏈接,偵聽單擊以查看它們是否起作用(將鏈接文本onClick加倍),並為每個鏈接分配click

preventDefault()用於防止每次單擊導航。

ES6語法用於更清晰的代碼。

 const links = document.getElementsByClassName('table-row'); const forEach = o => fn => Array.prototype.forEach.call(o, fn); const arr = []; forEach(links)((link, i) => { arr[i] = 'document.cookie = \\"cookieName='+link.href+'; path=/;"'; // listen to click just to be able to see it in action link.addEventListener('click', (e) => { e.preventDefault(); // for testing purposes const t = document.createTextNode(e.target.textContent); e.target.appendChild(t); }) // here you generate a click programmatically: const customClick = new MouseEvent('click', { "view": window, "bubbles": true, "cancelable": true }); link.dispatchEvent(customClick); // generate click }) 
 <table> <!--more rows here--> <tr> <td> <a class='table-row' href='/relative/path1'> Click1 </a> </td> <td> <a class='table-row' href='/relative/path2'> Click2 </a> </td> <td> <a class='table-row' href='/relative/path3'> Click3 </a> </td> </tr> <tr> <td> <a class='table-row' href='/relative/path4'> Click4 </a> </td> <td> <a class='table-row' href='/relative/path5'> Click5 </a> </td> <td> <a class='table-row' href='/relative/path6'> Click6 </a> </td> </tr> <!--more rows here--> </table> 

暫無
暫無

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

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