Webagg backend js bug (websocket not ready)

In matplotlib 3.3.3 the all_figures.html tornado template used by webagg contains:

          var websocket = new websocket_type("{{ ws_uri }}" + fig_id + "/ws");
          var fig = new mpl.figure(fig_id, websocket, mpl_ondownload, figure_div);
          fig.focus_on_mouseover = true;
          fig.canvas.setAttribute("tabindex", fig_id);
	}

However, this code may result in websocket not being ready/connected at the time that mpl.figure attempts to use it. Testing in Firefox, for example, yields Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable.

import matplotlib
matplotlib.use('webagg')

import matplotlib.pyplot as plt

matplotlib.rcParams['webagg.address']='0.0.0.0'
matplotlib.rcParams['webagg.port']=8988
matplotlib.rcParams['webagg.open_in_browser']=False

plt.plot([1,2,3])
plt.show()

then browse to http://localhost:8988 should yield the error in the javascript console. Nothing gets rendered.

To fix the problem, we wait for the socket to be open:

          var websocket = new websocket_type("{{ ws_uri }}" + fig_id + "/ws");
          websocket.onopen = function(e){
              var fig = new mpl.figure(fig_id, websocket, mpl_ondownload, figure_div);

              fig.focus_on_mouseover = true;

              fig.canvas.setAttribute("tabindex", fig_id);
          }

single_figure.html needs a similar fix.

Should I open a bug?

A.

What Matplotlib version are you using? I think this should be fixed on 3.3.4 and up. See webAgg example broken - maybe mpl.js broken? · Issue #19129 · matplotlib/matplotlib · GitHub

I did mention 3.3.3 :slight_smile: I looked at Issue #19129 and posted a link back to this discussion there. It’s not clear to me from the bug discussion whether or not 3.3.4 was changed to use onopen() to trigger mpl.figure() in the html templates for webagg. However, the bug was closed Dec 17 and the patch referenced seems to only avoid sending pixelratio, rather than solving the root cause (websocket not yet open).

If onopen() is not being used in 3.3.4 to trigger mpl.figure(), it maybe should be. My suggested fix above may in fact be causing the prior onopen() behavior not to ru (if, as implied by the discussion of issue #19129, there is an existing onopen()). In that case, calling the prior onopen() may be a necessary addition to my suggested fix.