Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - How can I call a javascript function in a website with selenium

So this is an element in a website

<span class="log-out-ico" ng-click="logout()">/

Let's say I don't want to click it, instead I just want to run the "logout()" script from selenium, Is it even possible? If so how?!

This is what I tried

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("logout()");

But I get this error :

javascript error: logout is not defined
question from:https://stackoverflow.com/questions/65929025/how-can-i-call-a-javascript-function-in-a-website-with-selenium

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Eg page:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="myCtrl">
  <p>Click the button to run a function:</p>
  <button ng-click="myFunc()">OK</button>
  <p>The button has been clicked {{count}} times.</p>
</div>

<script>
a=function(){
console.log("hiii")
}
angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.count = 0;
    $scope.myFunc = function() {
      $scope.count++;
    };
  }]);
</script>
</body>
</html>

You can see that the muFunc is not inside the script block but inside the Angular controller . You cannot call it directl.

But the function 'a' is normal javascript function so you call it directly .

call a and open browser console , you can see "hiiii" printed

THere are ways to expose angular function outside f the angular module but its not straight forward

Angular2 - how to call component function from outside the app


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...