How can I avoid state of “TypeError: can't access dead object” in my Firefox add-on?

白昼怎懂夜的黑 提交于 2019-11-27 07:08:46

问题


It seems checking against null works, but is it a correct method? How can I correctly check that object is not dead? And where is the definition of dead object?


回答1:


Dead object would mean an object whose parent document has been destroyed, and the references are removed to eliminate memory leaks in add-ons. So you could check for the element, as:

if( typeof some_element !== 'undefined') {
    //its not dead
}

See Dead Object Reference




回答2:


This is likely due to holding zombie compartments. If you are storing a window in a variable you should use weak reference, otherwise it will keep the process alive.

Great read right here:

https://developer.mozilla.org/en-US/docs/Zombie_compartments

This is how to use weak references: https://developer.mozilla.org/en-US/docs/Components.utils.getWeakReference

A dead object, is holding a strong (keep alive) reference to a DOM element (usually) that persists even after it was destroyed in the DOM.

Sometimes checking if it is undefined or null does not work, a trick I saw once and use sometimes is to check if parentNode exists (so not null or undefined).




回答3:


If you cannot use weak references as suggested by Blagoh, then you can use Components.utils.isDeadWrapper() function to check (added in Firefox 17 but still not really documented):

if (Components.utils.isDeadWrapper(element))
  alert("I won't touch that, it's a dead object");

Unprivileged code doesn't really have a way of recognizing dead objects without triggering an exception. Then again, if an object throws an exception no matter what you do then it is probably dead:

try
{
  String(element);
}
catch (e)
{
  alert("Better not touch that, it's likely a dead object");
}


来源:https://stackoverflow.com/questions/25041864/how-can-i-avoid-state-of-typeerror-cant-access-dead-object-in-my-firefox-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!