Copy selected text via a context menu option in a Chrome extension - javascript

I am trying to create a context menu option which copies some text to the system clipboard.
Currently, I am just copying a hard-coded string literal, but I am wondering how it could be changed to copy selected text. Specifically, I don't know how to properly create the createProperties object (see bottom)
It is my understanding that this can only be done through a background page.
I have the following background page:
background.html
<textarea id="temp"></textarea>
<script src="context.js"></script>
context.js is as follows:
chrome.contextMenus.create({
"title": "Freedom",
"contexts": ["editable"],
"onclick" : copyToClipboard
});
function copyToClipboard()
{
var tempNode = document.getElementById("temp");
tempNode.value = "some text";
tempNode.select();
var status = document.execCommand('copy',false,null);
if(status) alert('successful');
else alert('unsuccessful');
}
my manifest.json is as follows:
{
"manifest_version": 2,
"name": "Freedom",
"description": "Provides users useful and fun context menu options that they can access from anywhere.",
"version": "1.0",
"permissions": [
"contextMenus",
"clipboardWrite"
],
"background": {
"page": "background.html"
}
}
I am apparently declaring the chrome.contextMenus.create() function incorrectly. I have read the docs for it and I can only imagine that I am not properly creating the createProperties object.
I have been trying to mimic these sources:
Is that possible calling content script method by context menu item in Chrome extension?
http://paul.kinlan.me/chrome-extension-adding-context-menus/
some other related questions are:
Copy to Clipboard in Chrome Extension
How to copy text to clipboard from a Google Chrome extension?

"createProperties" in the documentation is the dictionary that is passed to the chrome.contextMenus.create method (i.e. that thing with "title", "contexts", etc.)
The onclick event description of chrome.contextMenus.create states that the function receives two parameters. The first parameter ("info") is a dictionary with information about the selected text. The second parameter ("tab") contains information about the tab (in your case, you don't need though).
The "info" dictionary has a property "selectionText" that holds the selected text when the context menu item was clicked. This can be used in your code as follows:
function copyToClipboard(info) {
var tempNode = document.getElementById("temp");
tempNode.value = info.selectionText; // <-- Selected text
tempNode.select();
document.execCommand('copy', false, null);
}
That would solve your immediate question.
Besides that, your extension can be improved by converting your background page to an event page. The main benefit of event pages over background pages is that your extension will not unnecessarily use memory while sitting idle in the background.
// background.js
// Register context menu
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
"id": "some id", // Required for event pages
"title": "Copy selected text to clipboard",
"contexts": ["editable"],
// "onclick" : ... // Removed in favor of chrome.contextMenus.onClicked
});
});
// Register a contextmenu click handler.
chrome.contextMenus.onClicked.addListener(copyToClipboard);
Here is a minimal manifest.json (note the "persistent": false key, which specifies that you want to use an event page)
{
"manifest_version": 2,
"name": "Copy selected text to clipboard",
"version": "1.0",
"permissions": [
"contextMenus",
"clipboardWrite"
],
"background": {
"page": "background.html",
"persistent": false
}
}

Related

Chrome extension: context menu icon not showing

I am building a Chrome extension and I set up a context menu which will show up and check the items (images or text) that the user selects from a table in the extension's popup.
This is my code for creating the context menu in popup.js's window.onload:
chrome.contextMenus.removeAll();
chrome.contextMenus.create( {title: "Toggle Selected",
documentUrlPatterns: [ "chrome-extension://*/popup.html"],
contexts:["selection"], onclick: toggleselected} );
This is the function that gets called on the context menu's onclick - also in popup.js (simplified version):
function toggleselected(info, tab)
{
var selection = window.getSelection(),
q0 = document.querySelectorAll("[id^='id0']"),
q1 = document.querySelectorAll("[id^='id1']");
for (var i = 0; i < somearray.length; i++)
{
if (selection.containsNode(q1[i], true))
{
somearray[i].checked = !somearray[i].checked;
q0[i].checked = !q0[i].checked;
}
}
updatesomearrayinfo();
}
And this is my manifest.json file (again, simplified version):
{
"manifest_version": 2,
"name": "Extension Name",
"version": "1.0",
"description": "Random description",
"browser_action":
{
"default_icon":
{
"16": "icon16.png",
"32": "icon32.png",
"48": "icon48.png",
"128": "icon128.png"
},
"default_popup": "popup.html"
},
"background":
{
"scripts": ["somescript.js"],
"persistent": true
},
"permissions": ["contextMenus", "tabs", "downloads", "<all_urls>"]
}
Everything works fine and the context menu correctly shows up when needed ... except that it doesn't have the extension's own icon next to it, but the default Chrome extension icon (the grey one). What can be done to correct this behavior? The icons in my manifest are ok, one of them (the 16x16 pixels, I believe) is correctly shown on my extension button, and apart from others usually doing the whole context menu thing from event pages, using chrome.runtime.onInstalled, contextMenus.onClicked.addListener and other listeners (which I am reluctant to use, since I specifically need to work with the variables from popup.js - e.g. somearray and queries on popup's elements), I don't seem to be doing anything different than things done by other extensions or the code samples in the answers here on StackOverflow. And they all get their own extension icons shown, apparently without doing anything special.
EDIT: Also, does anyone knows why the context menu for a selection is triggered only when the selection contains more than one specific item (an image, in my case)?

Chrome extension - page action: defining pages

I'm trying to build a somehow dummy Chrome extension. I want it to run only in specific pages, so I'm using a Page Action.
Let's say I want the page action to run on the Instagram website, then (accordingly the docs), I would need something like this on my manifest.json right?
{
"manifest_version": 2,
"name": "Some name",
"version": "0.0.3",
"description": "Some description",
"content_scripts": [
{
"matches": [
"https://www.instagram.com/*"
],
"js": ["content.js"]
}
],
"page_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
while the content script runs only on instagram pages as one would expect, the browser extension is not clickable (gray look, and when I click most options are not clickable).
this makes impossible to act upon extension button click. In my background.js I have:
function click(tab) {
console.log('click from ' + tab);
}
chrome.pageAction.onClicked.addListener(click);
that never gets called.
So, what's wrong that makes impossible to act upon extension click on some pages?
Note: I saw this question/answer, but couldn't find the problem/solution How can I add a click for pageAction?
You have to call pageAction.show in order for your pageAction button to be enabled (clickable).
The pageAction documentation says (emphasis mine):
You make a page action appear and be grayed out using the pageAction.show and pageAction.hide methods, respectively. By default, a page action appears grayed out. When you show it, you specify the tab in which the icon should appear. The icon remains visible until the tab is closed or starts displaying a different URL (because the user clicks a link, for example).
With a manifest.json content_scripts entry
Because you already have a content script that runs on the page you desire to have this function on, probably the easiest way to do this is to have your content script send a message to your background script telling it to show the page-action button for that tab.
Your content script could look something like:
chrome.runtime.sendMessage({type: showPageAction});
Your background script could look something like:
chrome.runtime.onMessage(function(message, sender, sendResponse) {
if(typeof message === 'object' && message.type === 'showPageAction') {
chrome.pageAction.show(sender.tab.id);
}
});
Without a manifest.json content_scripts entry
If you did not have a content script, you would probably want to use a webNavigation.onCompleted listener, or tabs.onUpdated listener, to listen for a change in the tab's URL in order to determine that the page-action button should be shown. Obviously, the trigger for calling pageAction.show() does not have to be the URL which is currently displayed in the tab, but that is the most common.

How to access a page element from a background js of chrome extension

I have a context menu in my chrome extension and now I need to capture a specific page elements when the user click on that menu.
This is my manifest file:
{
"manifest_version": 2,
"name": "Capture",
"description": "This extension is capturing all text elements in the page",
"version": "0.1",
"permissions": ["contextMenus"],
"background": {
"scripts": ["jquery-2.0.2.js", "background.js"]
},
"manifest_version": 2
}
background.js
function captureTextBoxes(e) {
var textboxes = $(':text') ;
//alert(textboxes.length);
textboxes.each(function (i){
//code here
}
}
chrome.contextMenus.create({
title: "Capture All text box Elements",
contexts:["page"],
onclick: captureTextBoxes,
});
This was capturing 0 text box elements always. So I checked the passed document by adding following line:
alert(document.documentElement.innerHTML);
It returns this :
<head></head>
<body style="">
<script src="jquery-2.0.2.js"></script>
<script src="background.js"></script>
</body>
This is not my actual page, but a dynamic page created by the chrome itself.
Is there anyway to access the actual page content that were right clicked for the context menu? (From a background javaScript)
The contextMenus.onClicked event (which triggers the callback specified by onclick (in persistent background pages only)) is only available to the background page and the background page has no direct access to any web-page's DOM.
If you want to manipulate the web-page DOM, you have to:
Inject a content script into the web-page.
Pass a message to that content script, so it can manipulate the DOM for you.
(There are plenty of resources here in SO explaining how to achieve both.)
Take, also, a look at this answer to a similar question

how do I activate a function in my chrome extension each time its tab becomes active

My background script is collecting data. I want it to update a table on the main page whenever it is in view. Is this possible?
You will need permission to access the tab data.
manifest.json:
{
"name": "My extension",
...
"permissions": [
"tabs"
],
...
}
Then you can use the onActivated event.
chrome.tabs.onActivated.addListener(callback)
More information here: http://developer.chrome.com/extensions/tabs.html

chrome extension's content script not working in google, youtube pages

I'm trying to create a chrome extension. When the user clicks my extension's icon (browserAction) the content script appends an extra div to the body of the open page(current tab). It works fine in all the sites except google's search page and youtube. I'm not getting any error message or anything. It simply wont give any response.
This is my code in content.js:
alert('sdsd');
$('body').append("<div id='popup'>My extension name</div>");
I've put the alert for testing purpose. So when extension is toggled it should show an alert message followed by appending the div to body, ideally! But it wont for these 2 sites.
Any idea what could be going wrong here?
manifest
{
"name": "My first extension",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"content_scripts": [{
"all_frames": true,
"css": ["style.css"],
"matches": ["http://*/*","https://*/*"]
}],
"permissions": [ "tabs","http://*/*" ],
"browser_action": { "name": "test" },
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.executeScript(null,{file:"jquery.min.js"},function(){
chrome.tabs.executeScript(null,{file:"content.js"});
});
});
In Youtube's page, $ is overwritten and isn't jQuery. It's
bound: function ()
{
return document.getElementById.apply(document, arguments)
}
So your code makes an exception as there document.getElementById('body') is undefined.
You should try using noConflict().
EDIT :
Why aren't you simply listing jQuery.min.js and your content.js in the content_scripts instead of injecting them programmatically. This would avoid conflicts.
EDIT 2 :
Now that you use content scripts, you should use communication as described here to send from background.js to the content script the instruction to show the alert.
EDIT 3 :
Another solution would have been to use programmatic injection (as you initially did) and not use jquery, $('body').append("<div id='popup'>My extension name</div>"); being translated in vanilla JS to
var div = document.createElement('div');
div.id = 'popup';
document.body.appendChild(div);
document.getElementById('popup').innerHTML = "My extension name"​;​
But it's generally cleaner (and requires less permissions) to avoid programmatic injection.

Categories