Running function inside document.write which document.write inside window.open

1.6k views Asked by At
function capture(){
  var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
  screenshot.document.write("<center/><img id='jpeg' src='"+img+"'><br/>");
  screenshot.document.write("<a download='vfr_capture.jpeg' href='"+img+"'>Download</a>");
  screenshot.document.write("<button id='myLink' onclick='popOut()'>Test</button>");
}
function popOut(){
  alert("Clicked");
}

Button myLink is appear after window.open, if i click it none happen. How can i make alert("Clicked") appear? Is it onclick function is disable inside document.write?

PS: I've tried to put function popOut() above the function capture(), but it still doesn't work. Please help.

2

There are 2 answers

1
T.J. Crowder On BEST ANSWER

The popOut in the onclick in the popup window is not the popOut in the current window. The two window environments are separate.

You can make it available to the other window, though, by adding this to the end of capture:

screenshot.popOut = popOut;

Live Example: (since Stack Snippets don't allow window.open)

document.querySelector('input').onclick = capture;
function capture(){
  var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
  /* Commented out since I don't have your `img` variable
  screenshot.document.write("<center/><img id='jpeg' src='"+img+"'><br/>");
  screenshot.document.write("<a download='vfr_capture.jpeg' href='"+img+"'>Download</a>");
  */
  screenshot.document.write("<button id='myLink' onclick='popOut()'>Test</button>");
  screenshot.popOut = popOut;
}
function popOut(){
  alert("Clicked");
}

HTML:

<input type="button" value="Click me">
0
Arun P Johny On

Both the functions are in different scopes

function capture() {
    var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
    screenshot.document.write("<center/><img id='jpeg' src='" + img + "'><br/>");
    screenshot.document.write("<a download='vfr_capture.jpeg' href='" + img + "'>Download</a>");
    screenshot.document.write("<button id='myLink'>Test</button>");

    screenshot.document.getElementById('myLink').onclick = popOut
}

Demo: Fiddle