Skip to content

Instantly share code, notes, and snippets.

@kumarasinghe
Created May 29, 2019 17:16
Show Gist options
  • Save kumarasinghe/b1adb3d4a736a089562d08131ee75273 to your computer and use it in GitHub Desktop.
Save kumarasinghe/b1adb3d4a736a089562d08131ee75273 to your computer and use it in GitHub Desktop.
Chrome Extension Content Script Access Global Variables & manipulate DOM
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)
}
let tabAddress = executeOnPageSpace('window.location.href')
alert('You are on: ' + tabAddress + '\nLets go somewhere else!')
executeOnPageSpace('window.location.href = "http://github.com"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment