# How Can Notebook Know When it Called by Another Notebook?

I would like a notebook to behave slightly differently depending on whether it is evaluated from another notebook; i.e.,

NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"]  How can the target notebook know when it has been called by another notebook? - If you put NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"] inside a Button, (i.e., Button["title", NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"] ]), then you can use ButtonNotebook[]=!=$Failed in the target notebook. –  kguler Dec 1 '14 at 15:39

Why not just set a symbol to have a value within the calling notebook? Something like...

$callingNotebook = EvaluationNotebook[];  Then in the called notebook see if$callingNotebook has a value.

-

I agree with @Ymareth that the simplest thing would be to have the calling notebook take explicit measures to communicate the context to the target notebook. However, if for some reason it is undesirable to alter the calling notebook, then here is another way.

When one notebook open in the front-end invokes another notebook, InputNotebook[] will normally return the calling notebook and EvaluationNotebook[] will return the target notebook. In contrast, if the target notebook is evaluated directly, then both expressions will return that single notebook. The target notebook could distinguish between the two cases by evaluating, for example:

If[InputNotebook[] === EvaluationNotebook[]
, (* action when invoked directly *)
, (* action when invoked from another notebook *)
]


This test is not 100% foolproof since one of the notebooks could contain code that expressly alters the InputNotebook[], or the calling notebook might be a palette (which is never the input notebook). But it is possible for this technique to be good enough for the circumstances that motivated the original post.

-