2

So we've got some old-school Firefox extension code that uses the DOM3 methods get/setUserData() to pass around data in the DOM. Unfortunately, these have been deprecated in DOM4, so Firefox is planning to drop support for them, and Chrome never supported them in the first place.

Is there a cross-browser replacement? jQuery's $.data seems to be an option, but 'pure' JavaScript would be preferable.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
lambshaanxy
  • 22,552
  • 10
  • 68
  • 92
  • Can't you just "steal" the implementation of `$.data`? – millimoose Jun 18 '12 at 01:07
  • We considered that, but it's surprisingly complex and tied to a lot of other jQuery functions: http://james.padolsey.com/jquery/#v=1.6.2&fn=data – lambshaanxy Jun 18 '12 at 03:11
  • 1
    Still a good question, jquery is the obvious solution but surely there has to be a non jquery solution as the original question asks! – Sydwell Aug 14 '13 at 08:23

3 Answers3

1

So in the end we decided to go with jQuery after all, the core library is only around 75k and it solves the problem very cleanly:

element.getUserData('foo') --> $(element).data('foo')

element.setUserData('foo', 'bar', null) --> $(element).data('foo', 'bar')
lambshaanxy
  • 22,552
  • 10
  • 68
  • 92
0

Use Custom event which can store data in the detail

Ref: How can I transfer data to firefox extension from web page

Community
  • 1
  • 1
Leslie Wu
  • 760
  • 3
  • 13
  • 29
0

Just set any property you want on the element.

element.key = value;

DOM elements/nodes are just JavaScript objects. To avoid name clashes with native properties (like id, etc.), you could prefix your keys with an underscore.

element._id = "foo";
rvighne
  • 20,755
  • 11
  • 51
  • 73
  • Have you actually tried this? Extensions are pretty severely sandboxed. – lambshaanxy Mar 09 '14 at 11:38
  • @jpatokal I haven't tried it, but this shouldn't cause any problems. If your jQuery solution works, then so will this, because both of them store properties direct on DOM objects. See the source: http://james.padolsey.com/jquery/#v=1.10.2&fn=_internalData – rvighne Mar 09 '14 at 19:15