繁体   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