点击并启动<a> element JavaScript

时间:2016-07-01 11:20:51

标签: javascript hyperlink click

I wouldlike to actuate an element with JavaScript, not only for call listeners, but also for open the link, like a user make with his mouse. I search a lot in Google, Stack..., Mozilla, I alway find that it's not possible, but there must have a way to do it ^^ I search also for an advanced option in Mozilla to disable it or something like that, but I found nothing

The code that I wouldlike to work like a real user click :

<a href="www.mysite.com" id="MyIdElement">Click here</a>
$('#MyIdElement').trigger('click');

or

document.getElementById('MyIdElement').click()

I know that Mozilla doesn't allow a Javascript click event on a <a> element : https://developer.mozilla.org/en/docs/Web/API/HTMLElement/click

The click() method will not cause an <a> element to initiate navigation as if a real mouse-click had been received.

我可以使用其他浏览器而不是Mozilla。我的最终目标是制作一个浏览器插件,可以像真实用户一样在网页绝对上导航,而不是windows.location.href,因为这不会发送所有信息,例如referer

由于

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你想在点击&#34; a&#34;时触发java脚本功能。元件。使用以下代码,您将在单击&#34; a&#34;元素并加载谷歌网站。

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <script>
        function myFunction(){
            window.alert("Test");
            };
    </script>
  </head>
  <body>
    <a href="http://google.com" onclick="myFunction()">Go to Google</a>
  </body>
</html>

整个事情都是通过这个代码块onclick="myFunction()"运行的,它只是通过点击运行定义的函数。我确定这适用于Chrome和IE。如果我理解你的问题不对,请纠正我,我会尽力回答。

答案 1 :(得分:1)

您可以使用以下脚本直接在dom元素上模拟事件鼠标单击(或其他)。这将模拟用户点击链接的方式。

实例,请注意点击您的链接将在您加载页面后立即执行: https://jsfiddle.net/pogdmb3m/

这适用于Chrome和FireFox(环绕其限制)。

var _triggerMouseEvent = function(node, eventType) {
  // create a syntetic mouse event
  var clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent(eventType, true, true);
  // dispatch event on your dom element
  node.dispatchEvent(clickEvent);
};

var elmDom = document.getElementById('MyIdElement');

_triggerMouseEvent(elmDom, 'click');