最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome Extension - Event Listener for Appended Code - Stack Overflow

programmeradmin4浏览0评论

I am writing a Chrome extension where I am trying to create a GUI on top of an existing page. This GUI consists of an input text field, and a reply button. I have created the GUI by creating an HTML string, and appending it to the website.

I want to add an event listener so that when the reply button is pressed, it will trigger a function so I can send the data in the input text field to my server. From my understanding, once code has been appended to the page, it no longer has access to script.js therefore it cannot access an event listener. Is there an alternative?

Image of my GUI: .php?pic=eventlistenermoot1328028688.jpg

I am writing a Chrome extension where I am trying to create a GUI on top of an existing page. This GUI consists of an input text field, and a reply button. I have created the GUI by creating an HTML string, and appending it to the website.

I want to add an event listener so that when the reply button is pressed, it will trigger a function so I can send the data in the input text field to my server. From my understanding, once code has been appended to the page, it no longer has access to script.js therefore it cannot access an event listener. Is there an alternative?

Image of my GUI: http://www.filedump/index.php?pic=eventlistenermoot1328028688.jpg

Share Improve this question edited Mar 23, 2022 at 21:59 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 31, 2012 at 16:57 JonJon 8,55131 gold badges96 silver badges150 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

The page you are injecting code into is sandboxed from content scripts. However your content scripts have full access to the page DOM, including events. That means that you can add an event listener to elements that you append. You have to add them unobtrusively so that the content script can then send a message to the background page:

Content Script:

var html = document.createElement('div');
    html.innerHTML = '<input id="clickMe" type="button" value="Click Me" />';
document.body.appendChild(html);

document.getElementById('clickMe').addEventListener('click', function() {
    // do stuff
});
发布评论

评论列表(0)

  1. 暂无评论