简体   繁体   中英

How to run function on new tab from main tab? (Google Chrome)

I need to open console and run one function on new tab, that I opened using javascrip. The opening part is easy, but how to run function on other tab?

 var google = window.open("http://google.com") 

Upon reading your question, it seems you're looking to open the dev console for the popup? Assuming this is what you're looking for, you should just be able to right-click the popped-up window and hit 'Inspect Element'. Then go to the console from there.


If you're trying to programatically run a function from the parent onto the popup window, here's an idea for you.

Assuming the new window is on the same domain as yours, this solution may work for you. (browser support is limited)

On the parent page:

//check if the function has been stored
if(typeof localStorage.runThis === "function"){
    //run the function in localStorage
    localStorage.runThis();
}

On the page to open in the popup:

 //check if the function has been stored if(typeof localStorage.runThis === "function"){ //run the function in localStorage localStorage.runThis(); } 

One issue is that this method relies on this criteria being met:

  • Browser supports localStorage
  • Parent page and Popup page come from the same origin
  • Popup page must actually look for the function in question and execute the function itself

One drawback of this is that if someone were to go to the Javascript Console and set their own function into localStorage, the popup page would see their function and run potentially dangerous code - a security hole.

A common solution is using localstorage .

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
  localStorage.setItem("lastname", "Smith");
  var lastname = localStorage.getItem("lastname");
} else {
    // Sorry! No Web Storage support..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM