简体   繁体   中英

Add event, through extension, to an element with event handler function in original page

In my Content Script, I have an element (an a tag, to be more specific) and I need to add an event to it. The event handler, however, is defined in the page JS, and I dont know how to attach it to the event of my element in the extension. What I want to achieve is:

element.addEventListener("mouseover", pageFunction("foo", "bar"));

I have read other questions, like this one , which suggests injecting code or using location.href="javascript:pageFunction(); void 0"; but I dont see how I could apply them in my case.

According to the MDN reference there is a way for page and content scripts to communicate with each other .

In Firefox*, DOM objects in content scripts get an extra property wrappedJSObject . This is an "unwrapped" version of the object, which includes any changes made to that object by any page scripts.

Now, in your code, you're immediately calling the function rather than passing the listener a reference. To solve this you should wrap your function call in an arrow function to prevent this:

element.addEventListener("mouseover", () => window.wrappedJSObject.pageFunction("foo", "bar"), false);

∗ I couldn't find any information about whether this method should be used for Chrome too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM