I saw this post regarding the script unload function but you’d have to code this in before you hit the problem:
Maybe that would help?