0

I want to create an image element that, when clicked, opens a blank browser window with a specified background:

<img src="http://example/image1.jpg" onclick="var w=window.open('','_blank');w.document.body.style.backgroundColor='url("http://example/image2.jpg")'">

However, I cannot get the above to work using either ", ', or \xXX (hex) for url("http://example/image1.jpg"), since both " and ' are already used for quoting in outer scope.

What to do?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • 4
    Easiest solution: [don't put event listeners in your HTML document](https://stackoverflow.com/q/6941483/1048572)! If you still need to, then HTML-escape them as `&quote;` within your `"`-delimited attribute value. – Bergi Aug 16 '19 at 08:40
  • there is something like `escape` sequence which you are using like `\"` – noname Aug 16 '19 at 08:40
  • @Bergi - why does `&quote;` work? Everything in `onclick` is in JavaScript context, and `&quote;` is for HTML, right? – Shuzheng Aug 16 '19 at 08:42
  • @Shuzheng Because `` is HTML, leading to a value of `…"…` for the attribute. The HTML parser doesn't have a "JavaScript context", the attribute value must be valid JS code. – Bergi Aug 16 '19 at 08:45
  • 1
    @Bergi - Ohh, so the HTML parser converts `…&quote;` to `"` **everywhere** (attributes etc.) in the HTML page - and the resulting attribute value is evaluted as JS code when clicked? – Shuzheng Aug 16 '19 at 09:12

1 Answers1

3

Remove the inline handler (they're generally considered to be quite poor practice anyway) and add the listener properly using Javascript instead, and you won't have to worry about having to escape due to HTML markup:

const img = document.querySelector('img'); // feel free to make this more precise as needed
img.addEventListener('click', () => {
  var w = window.open('','_blank');
  w.document.body.style.backgroundColor = 'url("http://example/image2.jpg")';
  // alert('HelloWorld')">
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320