0

Say I am opening a webpage (www.facebook.com) by passing the url to window.open() function. My window opens as a new browser since I have used "_blank" in window.open() function.

I want to run my own javascript on the newly opened window. When I researched, found some solution which I have added in my source code as posted below. But unfortunately my javascript is not working on the newly opened window. Could someone help me in this ?

<!DOCTYPE html>
<html>
<head>
<script>

 function myFunction() {
  var url = document.getElementById("myText").value
  var newWindow = window.open(url,'_blank','height=400,width=600,left=10,top=10,scrollbars=yes,menubar=yes,titlebar=yes')
  var newScript = newWindow.document.createElement('script');
  //console.log(newScript);
  newScript.setAttribute('type','text/javascript');
  newScript.setAttribute('src','C:/Users/30216/Desktop/jquery_edited_new1.js');
  newWindow.document.getElementsByTagName("head")[0].appendChild(newScript);
  //console.log(newWindow);
  //newWindow.document.head.appendChild(newScript);
  
}
  
</script>
</head>
<body>
<table align = "center">
<frame>
<tr>
 <td class="url">Enter the URL:</td>
 <td>
  <input type="text" id="myText"></input>
 </td>
</tr>
<tr>
 <td>
  <button id="browser_open" onclick = "myFunction()">Submit</button>
 </td>
</tr>
</frame>

</body>
</html>

 
Dij
  • 9,761
  • 4
  • 18
  • 35
  • You can't do that. Clear cross origin violation (read about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). If you think you will just simply open a Facebook login page from your site and catch user's login information then haha, forget about it. ;) – Jan Peša Jul 26 '17 at 10:52
  • If you want to run your own JavaScript on a webpage of your choosing then the TamperMonkey/GreaseMonkey plugins are what you want. – Phylogenesis Jul 26 '17 at 11:00

1 Answers1

1

You can only access the document according to the Same-Origin-Policy.

If you open another web page like Facebook and the webpage that opened facebook.com does not use the same domain, protocol and port it will not be able to access the document of that page.

Imagine what you could do if you without this policy. E.g. you would be able to open Facebook, secretly install a key logger and tell the user to log in.

idmean
  • 14,540
  • 9
  • 54
  • 83
  • Can it be achieved if I am running my HTML on a webserver as mentioned in this stackoverflow link: https://stackoverflow.com/questions/29983786/blocked-a-frame-of-origin-null-from-accessing-a-cross-origin-frame-chrome: @idmean – Karthikeyan Jul 27 '17 at 05:13
  • @Karthikeyan It’s very simple: If your website has the same domain, port and protocol as the window you open (i.e. it’s the same site) it works otherwise not. The answer you linked just concerns development. That’s for security reasons and there is (should be) no way to circumvent this. – idmean Jul 27 '17 at 15:21