What you're requesting is not possible yet, but there are two feature requests that would make it possible to achieve your goals when they are implemented:
Today
Since you want to create a page-specific context menu, you could check whether the page contains that variable, then send the URL to the background page, which in turn registers a context menu for that specific URL pattern (see documentUrlPatterns
). This would only work if you want to show the context menu on a page that has a relatively unique URL.
To detect whether the page has a window.foo
variable, and communicate the information to the background page, see this answer.
Future
I expect that a declarative context menu will be implemented, so your extension should tell Chrome upfront that a context menu has to be rendered. If the second feature request gets implemented, then the extension can add an attribute to the document to trigger get the desired context menu.
Assuming that it is possible to declaratively toggle the context menu, then you have to overcome another hurdle: The page's window.foo
variable is not directly visible to the content script (let alone the background page). So you have to run code in the context of the page, e.g. using one of the methods described in this answer and then use e.g. document.documentElement.setAttribute
to set an attribute that would be matched by the to-be-implemented contextMenus API extension.