简体   繁体   中英

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 simulate 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');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM