0

I have a tab with an object defined on the window.

window.foo = 'bar';

Using chrome.contextMenus api, I'd like to create menu items off of the window.foo value.

The goal is to obtain this information without registering a click event on prexisting context menu item. How do I obtain the window object on page load, successfully passing it to the context api?

random-forest-cat
  • 33,652
  • 11
  • 120
  • 99

1 Answers1

1

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.

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678