javascripthtmlgoogle-chromeobject-tag

Chrome not reloading object tag after linking to nonexistent file


I have the following index.html. The objective of the javascript below is to reload the #obj element's data tag, so that it can display multiple images. However, it is possible that one of the images I link the buttons to doesn't exist (in this case, #2).

function updateObject(evt) {
    var id = evt.currentTarget.id;
    var object = document.getElementById("obj");

    if (id == "1") {
          object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
    }
    else {
        object.setAttribute("data", "file/that/doesnt/exist")
    }
}

for (var i = 0; i <   document.getElementsByTagName("button").length; i++) {
    document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    </head>
    <body>
        <button id="1">button1</button>
        <button id="2">button2</button>
        <object id="obj" style='width: 100px'></object>
    </body>
</html>

What I expect to happen in the following script is this:

However, the third step in that doesn't happen - when I try to reload the object's data after linking to a nonexistent file, it stays blank.

As far as I've been able to gather, this happens in Chrome, and for me works in Safari. I must use the object tag, or some other method that allows for interactive SVG.


Solution

  • One solution you could possibily do is to remove and add the node itself to force a hard reset

    var clone = object.cloneNode();
    var parent = object.parentNode;
    parent.removeChild(object);
    parent.appendChild(clone);
    

    function updateObject(evt) {
      var id = evt.currentTarget.id;
      var object = document.getElementById("obj");
    
      if (id == "1") {
        object.setAttribute("data", "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
        var clone = object.cloneNode();
        var parent = object.parentNode;
        parent.removeChild(object);
        parent.appendChild(clone);
      } else {
        object.setAttribute("data", "file/that/doesnt/exist")
      }
    }
    
    for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
      document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
    }
    <button id="1">button1</button>
    <button id="2">button2</button>
    <object id="obj" style='width: 100px'></object>