0

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.

1
  • 3
    a) That's very invalid HTML b) Whatever is behind the link doesn't matter at all, PHP is of no concern here. Commented Sep 25, 2011 at 9:40

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.