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

非 Y 不嫁゛ 提交于 2019-12-30 11:51:29

问题


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")

回答1:


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:

//store the function in localStorage
localStorage.runThis = function(){ alert("Hello world"); }
//open the popup window
newWindow = window.open("http://your-domain.com/your-page");

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.




回答2:


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..
}


来源:https://stackoverflow.com/questions/38213746/how-to-run-function-on-new-tab-from-main-tab-google-chrome

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