You can also utilize sessionStorage
and localStorage
, which are available in the JavaScript standard library. These solutions are purely JavaScript-based and do not rely on WEM view state internals. Let's update our previous widget slightly.
Update the script with the following:
In this update, we introduce startupscript
, which is a JavaScript code block that runs after the page has been initialized and all static HTML elements are rendered. We also have unloadscript
, which executes when a WEM event is triggered, just before the new page is rendered. We will discuss these script blocks in more detail in later chapters.
Comparing the previous code with the new version, you will notice that the initializeMessageBox()
function is used to initialize the message box, as the name suggests. Here, we set the class names and retrieve the view state using sessionStorage
through JavaScript. Additionally, we updated the code to set the click
handler here instead of using an onclick
attribute. While functionally there is no difference, this approach promotes better organization, a principle known in computer science as "separation of concerns."
Looking at the function getKeyMessageBox(outputId, nodeId)
and the line const key =
${element.id}:${nodeId}:collapsed;
, we see that the key
is created by combining the Output ID, a node ID, and an arbitrary identifier, separated by a colon. Since sessionStorage
keys are stored globally, we need to ensure that the keys for this widget are globally unique. If we had simply used "collapsed" as the key and had two identical widgets on the same page, they would overwrite each other's state. The node ID ensures that the view state of this widget is unique per interaction node. While we use a colon here, any character that is not alphanumeric can be used, as those characters are reserved for the Output ID and node ID.
Depending on the widget you are creating, you may want to clear the view state—demonstrated using clearStateMessageBox()
here—when unloading the widget.