简体   繁体   中英

Is it possible to execute a javascript in a new window with window.location.href?

I am trying to open a new window and execute a javascript code on the new page.

I'm not really sure why it doesn't execute the code - maybe it's not possible like this - anyway, the new window opens but the javascript doesn't get executed.

Here is my code:

var nstart = window.open(" http://examplepage.html ");

function loginnow(){
var htmlstring = "javascript: var zTextFields = window.document.getElementsByTagName(\"input\"); for (var i=0; i < zTextFields.length; i++) {thefield=zTextFields[i].name; if (!thefield) thefield=zTextFields[i].id; if (thefield == \"login\") zTextFields[i].value=\"_ext_cancom\"; if (thefield == \"password\")zTextFields[i].value=\"canfinag?!\";} window.document.getElementById(\"sign-in\").click();";

nstart.location.href = htmlstring;
}

nstart.addEventListener('load', loginnow, true);

Is it even possible to execute code like this? Please help ^-^ I'm also using '\\' as an escape character so I can use " in the string -> \\"

When I replace the \\" with " and directly inject it into the page the script works fine...

Maybe you can add the javascript you want to execute in the new new page, and then make it run when document ready . So you will can just open the new page, JS will run automatically

If the new window is on the same domain you can access the contents by doing something like this.

var nstart = window.open("http://examplepage.html");

function loginnow() {
  var zTextFields = nstart.document.getElementsByTagName("input"); 
  for (var i=0; i < zTextFields.length; i++) {
    thefield=zTextFields[i].name;
    if (!thefield) 
      thefield=zTextFields[i].id; 
    if (thefield == "login") 
      zTextFields[i].value="_ext_cancom"; 
    if (thefield == "password")
      zTextFields[i].value="canfinag?!";
  } 
  nstart.document.getElementById("sign-in").click();
}

nstart.addEventListener('load', loginnow, true);

You shouldn't really try to inject code onto the new window but you can access the dom and run javascript from the parent window.

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