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.
NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"]
inside aButton
, (i.e.,Button["title", NotebookEvaluate[$UserDocumentsDirectory <> "/Mathematica/notebook.nb"] ]
), then you can useButtonNotebook[]=!= $Failed
in the target notebook. $\endgroup$