4

I am working on a browser extension that will automatically click a button on a page. The code works on every site except ones with angularjs.

The following code is my attempt at clicking an angularjs button and have it register the click, but it does not work.

//applyButton is the button element.
if(angular) {
     var e = angular.element(applyButton);
     e.trigger('click');
     e.scope().$apply();
 } else {
     applyButton.click();
 }

Here is the angular html code for the applyButton that is not registering the "click"

<input value="Apply" class="apply button gift-card-apply" data-ng-click="!orderSubmitErrors.giftCard.sectionHasErrors &amp;&amp; applyGiftCard($event)" client-validation="onSubmit,giftCard,validateSubsection" type="button">

Is there a best practice to click buttons and change input fields for angularjs from javascript if I only have access to the document.element for those items?

1
  • does element exist when your code runs? Can't use conventional page load handling Commented Sep 14, 2015 at 21:47

1 Answer 1

1

It seems you need to wrap your element in a $timeout to invoke a .click on your element. Observe the following simplified example...

<div ng-app="app" ng-controller="ctrl">
    <button id="btn" ng-click="click()">click</button>
</div>

var app = angular.module('app', []).controller('ctrl', function($scope, $timeout) {
    $scope.click = function() {
        console.log('click');
    }

    $timeout(function() {
        angular.element(document.getElementById('btn')).trigger('click')
    });

    //does not work
    angular.element(document.getElementById('btn')).trigger('click')
});

With this, you will not be needing to call e.scope().$apply(); - $timeout will invoke a cycle if necessary. Additionally, while you didn't specify in your example, its worth nothing that .trigger() requires jQuery and is not baked into AngularJS's jqLite.

JSFiddle Link - demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the code example, for some reason I can't get past $timeout...it hangs when it sees it. But if(angular) is true. Also the jsfiddle seems to not be loading angular maybe jsfiddle is down.
are you injecting $timeout into your controller? The fiddle seems to be working could you try again?
example works in chrome but not firefox for some reason on jsfiddle. So I can see it working now. Thanks for the example. I understand how it is working now after playing with it.

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.