开发者

how to use javascript to simulate click on link where href is php

I am writing a Google Chrome Extension. I need to use javascript to sim开发者_JAVA百科ulate a click on this link: <a href="/logout.php /a> so I can log out. How can I get this done?

No JQuery please, I haven't learned it yet.


Main function will create any event:

   function ShowOperationMessage(obj, evt) {
        var fireOnThis = obj;
        if (document.createEvent) {
            var evObj = document.createEvent('MouseEvents');
            evObj.initEvent(evt, true, false);
            fireOnThis.dispatchEvent(evObj);
        } else if (document.createEventObject) {
            fireOnThis.fireEvent('on' + evt);
        }
    }

Now call the function:

 ShowOperationMessage(document.getElementById("linkID"), "click");


Since this is for an extension, you could submit an XHR request to the server /logout.php rather than simulate a click.

But simulating a mouse click is rather simple, I use the following code in many of my extensions:

function simulateClick(element) {
  if (!element) return;
  var dispatchEvent = function (elt, name) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent(name, true, true);
    elt.dispatchEvent(clickEvent);
  };
  dispatchEvent(element, 'mouseover');
  dispatchEvent(element, 'mousedown');
  dispatchEvent(element, 'click');
  dispatchEvent(element, 'mouseup');
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜