You could dispatch a bubbling event, and use the event.target
property to get the node's reference:
// content script
var myEventName = 'whatever' + Math.random(); // Unpredictable, avoid conflicts
document.addEventListener(myEventName, function(event) {
event.stopPropagation(); // No need to bubble further
var element = event.target;
// ... rest of your code
}, true); // <-- Get event at capture phase
// Inject the injected script
var script = document.createElement('script');
script.textContent = '(' + function(myEventName) {
function sendElementToContentScript(element) {
var event = new CustomEvent(myEventName, { bubbles: true });
element.dispatchEvent(event);
}
// ... rest of your code, e.g. sendElementToContentScript(document.body);
} + ')("' + myEventName + '");';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
If you wish to pass additional information with the event, set the event.detail
property:
// set
var event = new CustomEvent(myEventName, {
bubbles: true,
detail: 'any serializable type'
});
// read (in event listener
console.log( event.detail );
For more information, see CustomEvent
(MDN) and Building a Chrome Extension - Inject code in a page using a Content script (for those who are unfamiliar with the script injection technique).