javascriptjqueryhtmlcross-window-scripting

.data() html5 cross window


I'm trying to put some data into a child windows html tag. But it doesn't seem to work. I tried putting it in with some jquery on that child window and that is working fine.

Here is the code implemented in the parent window to send the data to the child window:

$(".something", fullscreen.document).data("data1", "whatever");

Which will return "undefined" with the following jQuery code in the child window.

console.log($(".something").data("data1"));

But when I store the data with the child jQuery-script it works perfectly:

$(".something").data("data1", "whatever");

Is crosswindow data storing into tags not allowed?


Solution

  • jQuery uses its own data store for data you set with .data(). Each instance of jQuery (in each window) will have it's own separate data store so you won't get results from one when calling from another.

    If your data is simply a string, then you will probably find it easier to not worry about multiple instance data stores and just use .attr() to store the string as an actual attribute on the DOM object. Then, there's zero question about where it's stored or how to access it because it's directly on the DOM object which you can easily get to from either jQuery instance.

    // store data on the object
    $(".something", fullscreen.document).attr("data-data1", "whatever");
    
    // read data from within the target window
    console.log($(".something").attr("data-data1"));
    

    Note the use of the HTML5 "data-xxx" convention to avoid any attribute naming conflicts with standard attributes.