Question

How would I go about calling my function in a way that it is always running. I want to get the text selection wherever the user double clicks. So I don't know how to attach the eventlistener that always stays on. not just a one time function when the document is loaded. but more like an ongoing eventlistener as long as the tab is open?

Thanks you so much!

Était-ce utile?

La solution

In order to achieve what you describe (and to have it always available on every tab), you can use a content script and have it injected in every page (see code below).
If you want it to be bound to a specific tab only, you can utilize an event page (i.e. a non-persistent background page) and register a listener for the chrome.tabs.onUpdated event and programmatically inject the content script every time a new page is loaded in the specified tab.

In the aforementioned content script, you can attach an event-listener to the document itself to capture all events.


Below is the source code of a sample extension that adds the desired "feature" to every tab:

content.js

var listener = function(evt) {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        var text = range.cloneContents().textContent;
        console.log(text);
    }
};
document.addEventListener('dblclick', listener);

manifest.json

{
    "manifest_version": 2,

    "name":    "Test Extension",
    "version": "0.0",
    "offline_enabled": true,

    "content_scripts": [{
        "matches":    ["<all_urls>"],
        "js":         ["content.js"],
        "run_at":     "document_end",
        "all_frames": false
    }]
}

Autres conseils

Ok, so to call the javascript on a persistent manner, you must define a contentScript and call the js from there. http://net.tutsplus.com/tutorials/javascript-ajax/developing-google-chrome-extensions/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top