How can we know if a function is called from console or from source code

后端 未结 3 842
青春惊慌失措
青春惊慌失措 2020-12-16 05:37

I want to know if there is a way to check if a javascript function is being called from console of the browser or from source code.

I defined a function that can ch

3条回答
  •  孤街浪徒
    2020-12-16 06:04

    For Chrome, you could just check to see if the keys function is available. It's part of chrome's Command Line API and only available when the code was executed from the console

    function myFunction() {
      var fromConsole = typeof keys === 'function' && keys.toString().indexOf('Command Line API') !== -1
      if (fromConsole) {
        alert('From console')
      } else {
        alert('Not from console')
      }
    }
    

提交回复
热议问题