在不单击实际链接按钮的情况下运行某个链接

时间:2017-05-05 16:51:20

标签: javascript

我正在尝试编写一个替换当前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>

2 个答案:

答案 0 :(得分:0)

使用forEach在数组内循环。将el关联到cookie并更改数组元素。然后触发点击具有所需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');
});

答案 1 :(得分:0)

您可以创建新的click事件,并将其分配给下面的代码。

在此示例中,我们遍历所有与类table-row的链接,听取点击以查看它们是否有效(点击链接文本加倍),并为每个链接发送click

preventDefault()用于阻止每次点击导航。

ES6语法用于更清晰的代码。

&#13;
&#13;
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
})
&#13;
<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>
&#13;
&#13;
&#13;