Chrome extension - retrieving global variable from webpage

后端 未结 5 1761
离开以前
离开以前 2020-11-22 17:10

I am working on an extension for Chrome. I wish parse the content of the \"original\" Gmail message (the currently viewed message).

I tried to utilize the jQuery.loa

5条回答
  •  青春惊慌失措
    2020-11-22 17:56

    Add to your content script:

    function executeOnPageSpace(code){
    
      // create a script tag
      var script = document.createElement('script')
      script.id = 'tmpScript'
      // place the code inside the script. later replace it with execution result.
      script.textContent = 
      'document.getElementById("tmpScript").textContent = JSON.stringify(' + code + ')'
      // attach the script to page
      document.documentElement.appendChild(script)
      // collect execution results
      let result = document.getElementById("tmpScript").textContent
      // remove script from page
      script.remove()
      return JSON.parse(result)
    
    }
    

    Now you can do:

    let window = executeOnPageSpace('window')
    

    or even like this:

    executeOnPageSpace('window.location.href = "http://stackoverflow.com"')
    

    NOTE: I have not tested this for long-running code.

提交回复
热议问题