Javascript: Retrieve file and line location of function during runtime

。_饼干妹妹 提交于 2019-12-13 20:22:09

问题


I am trying to get the file and line location of a function I saved in an object. If I am logging the object to the Chrome Dev Tools I see this:

Can I somehow from inside the code access [[FunctionLocation]]? Or is this something the Chrome Dev Tools add to the object? If so, is it possible to retrieve the function location when I am developing a Chrome Dev Tools extension or a Chrome extension?


回答1:


  1. You still cannot access the internal properties through JavaScript.

  2. The information is exposed through the Chrome DevTools Protocol, as an InternalPropertyDescriptor. This is observable through for example Node.js:

    global.a = () => { /* test function */ };
    
    const s = new (require('inspector').Session)();
    s.connect();
    
    let objectId;
    s.post('Runtime.evaluate', { expression: 'a' }, (err, { result }) => {
      objectId = result.objectId;
    });
    s.post('Runtime.getProperties', { objectId }, (err, { internalProperties }) => {
      console.log(internalProperties);
    });
    

    yields

    [
      {
        name: '[[FunctionLocation]]',
        value: {
          type: 'object',
          subtype: 'internal#location',
          value: [Object],
          description: 'Object'
        }
      },
      {
        name: '[[Scopes]]',
        value: {
          type: 'object',
          subtype: 'internal#scopeList',
          className: 'Array',
          description: 'Scopes[2]',
          objectId: '{"injectedScriptId":1,"id":24}'
        }
      }
    ]
    

    with Node.js v12.3.1.

    Chrome extensions may interact with the Chrome DevTools protocol through chrome.debugger. I am not familiar with how DevTools extensions work, but you may find the Integrating with DevTools page to be insightful.



来源:https://stackoverflow.com/questions/56066523/javascript-retrieve-file-and-line-location-of-function-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!