开发者

How can you gain access to a web page's event listeners from a Google Chrome extension

I'm writing a Chrome extension to list out the source code for each event handler attached to an <a/> tag when you roll over it.

Currently, I've printed out the href attribute - $(this).attr("href") - and this works fine. The source code is on github at http://github.com/grantyb/Google-Chrome-Link-URL-Extension.

When I extend it to access event handlers, $(this).data("events") returns null. I'm certain that there is a click() handler for my <a/> tag, because when I output $("a").data("events") inside my web page, it correctly lists the handler.

It seems that jQuery's data() method is checking data that is sandboxed, so I can't acce开发者_JAVA百科ss it from inside my Extension. That makes sense, since I guess it's stored within the jQuery global variable, and that's clearly a different variable from the jQuery global that lives inside my Extension.

Is there another way to access the list of event handlers for an object in the DOM. Are event handlers even stored in the DOM?


Solved with a terrific hack!

Check out the code on GitHub for the details: http://github.com/grantyb/Google-Chrome-Link-URL-Extension.

The Content Script uses jQuery to append a <script> tag directly into the host page (insert maniacal laugh here). The "parasite" script has complete visibility over the host page, including DOM and javascript sandbox, since it is now a part of the page. It fetches the data I need, encodes it into a text format and writes it into an attribute of an element that I prepared earlier.

Then, I sit back and wait (setTimeout(...,10)) for the script to do its business. When I get called back, I clean up after myself and grab the text-encoded data straight out of the DOM element.

Is there an easier way? This feels naughty.


Your entire extension is sandboxed. You can access the DOM from your extension, but not the javascript.

The only way to interact is by modifying the DOM in such a way that your javascript loads inside the webpage. But you'll still be sandboxed so you can't communicate with your extension via javascript directly.


As WoLpH said, your extension is sandboxed and can't access nor modify any webpage DOM.

Still, you can achieve your goal "gracefully" by using a content script and message passing:

  • A content script for accessing/modifying the webpages DOM
  • Message passing for communication between your extension and the webpages
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜