N
N
Ninazu2015-01-09 03:26:43
JavaScript
Ninazu, 2015-01-09 03:26:43

Chrome Extension how to insert text?

I'm trying to write an Extension for Chrome. Created a context menu. How can I insert text into a textarea when clicking on a menu?

function addText (info, tab) {
        console.log(info, tab);
}
chrome.contextMenus.create({
            'contexts': ['editable'],
            'onclick': addText
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shqn, 2015-01-12
@shqn

As I understand it, the context menu will be called only on this very textarea. Then you can write something like this, remembering the element on which the right click occurred.
1. content.js

var AppContent = {
    init: function() {
        document.body.addEventListener("contextmenu", function(event) {
            chrome.runtime.sendMessage({action: "rememberTarget", data: event.target});
        });
    }
};
AppContent.init();

2. background.js
var AppBackground = {
    target: null,
    init: function() {
        chrome.runtime.onMessage.addListener(function(request) {
            if(request.action === "rememberTarget")
                this.target = request.data;
        }.bind(this));
        
        chrome.contextMenus.create({
            'contexts': ['editable'],
            'onclick': function() {
                if(this.target)
                    this.target.value = "some text";
            }.bind(this)
        });
    }
}
AppBackground.init();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question