I wanna make an extension that takes the selected text and searches it in google translate
but I can't figure out how to get the selected text.
Here is my manifest.json
{
"manifest_version": 2,
"name": "Saeed Translate",
"version": "1",
"description": "Saeed Translate for Chrome",
"icons": {
"16": "icon.png"
},
"content_scripts": [ {
"all_frames": true,
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"background",
"tabs"
]
}
and my background.js file
var text = "http://translate.google.com/#auto/fa/";
function onRequest(request, sender, sendResponse) {
text = "http://translate.google.com/#auto/fa/";
text = text + request.action.toString();
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.create({url:text});
});
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]});
and my content_script.js file
var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
console.log('Start action sent');
});
How do I get the selected text?
You are making it a bit more complicated than it really is. You don't need to use a message between the content script and background page because the contextMenus.create method already can capture selected text. Try adjusting your creations script to something like:
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
Then adjust your function to simply get the info.selectionText:
function onRequest(info, tab) {
var selection = info.selectionText;
//do something with the selection
};
Please note if you want to remotely access an external site like google translate you may need to adjust your permissions settings.
I would note - this is no longer valid response if you are moving to manifest version 3. Manifest version 3 adds the concept of "service workers". https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/
You have to update several things, but the basic concept is the same.
manifest.json
"name": "Name of Extension",
"version": "1.0",
"manifest_version": 3,
"description": "Description of Extension",
"permissions": [
"contextMenus",
"tabs",
"activeTab"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
background.js
//Setting up the function to open the new tab
function newTab(info,tab)
{
const { menuItemId } = info
if (menuItemId === 'anyNameWillDo'){
chrome.tabs.create({
url: "http://translate.google.com/#auto/fa/" + info.selectionText.trim()
})}};
//create context menu options. the 'on click' command is no longer valid in manifest version 3
chrome.contextMenus.create({
title: "Title of Option",
id: "anyNameWillDo",
contexts: ["selection"]
});
//This tells the context menu what function to run when the option is selected
chrome.contextMenus.onClicked.addListener(newTab);
Related
I am working on a chrome extension that will enable user to click on an added button to inform me of their interest.
Basically, I built a chrome extension which displays a toolbar and I want the user to be able to click on this toolbar and execute a script after it.
Here are my codes and it does not work...
manifest.json file :
{
"manifest_version": 2,
"name": "XX Extension",
"version": "1.0",
"description": "The best extension for my friends",
"icons":{
"128" : "images/icon128.png",
"48" : "images/icon48.png",
"16" : "images/icon16.png"
},
"background": {
"scripts": ["js/jquery-3.4.1.min.js", "js/background.js"]
},
"permissions": [
"contextMenus",
"activeTab",
"tabs",
"notifications"
],
"content_scripts": [
{
"matches": ["https://www.mysite.fr/produit/*", "*://*.mysite.fr/produit/*"],
"css": ["css/extension_style.css"],
"js": ["js/jquery-3.4.1.min.js", "js/content.js"]
}
],
"browser_action": {
"default_icon": "images/icon16.png",
"default_title": "XX Extension",
"default_popup": "popup.html"
},
"web_accessible_resources": [
"toolbar.html",
"css/extension_style.css"
]
}
content.js file :
var script_text=$("script:contains(['ean'])").html();
var product_ean=script_text.split("['product']['ean']")[1].split(";")[0].replace("= '","").replace("'","");
chrome.runtime.sendMessage(product_ean);
var url = chrome.extension.getURL('toolbar.html');
var height= '35px';
var iframe = "<iframe src='"+url+"' id='myOwnCustomToolBar_TT91' style='height:"+height+"'></iframe>";
$('html').append(iframe);
$('body').css('transform','translateY('+height+')');
/* Topbar clicked */
$('#myOwnCustomToolBar_TT91').on('click', function(){
alert('it is clicked');
// do stuff executing js script
});
background.js file :
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
alert("Le code EAN de ce produit RDC est "+response);
});
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.executeScript(null, {
code : "alert('Wow it is working guy');"
});
});
The chrome extension work well to alert the EAN code of the product but the click event on the appended topbar by the extension does not work...
Thank you very much for your feedback and help !
Best regards,
I have a toggling function, in background.js: every time a user clicks the icon, if the extension was turned off, it is turned on, and if extension was turned on, is now off, and the icon swaps to reveal which of those states it's in. "image1" revealing that it's turned off and "image2" revealing it's turned on. However, the function only updates icon URL once when clicked, despite the fact that it continually fires from "onclicked" event as evidenced by chrome dev console. Any ideas?
Here is what's in background.js:
var off = true;
function updateIcon() {
if (off == true) {
off = false;
chrome.browserAction.setIcon({path:"image1.png"});
console.log(off);
}
else {
off = true;
chrome.browserAction.setIcon({path:"image2.png"});
console.log(off);
}
return;
}
chrome.browserAction.onClicked.addListener(updateIcon);
updateIcon();
And my manifest.json file:
{
"background": {
"scripts": [ "jquery-3.1.1.min.js", "background.js" ]
},
"browser_action": {
"default_icon": "image1.png"
},
"content_scripts": [ {
"css": [ "style.css" ],
"js": [ "jquery-3.1.1.min.js", "content.js"],
"matches": [ "https://www.facebook.com/*", "http://www.facebook.com/*", "http://facebook.com/*", "https://facebook.com/*"],
"all_frames" : true,
"run_at" : "document_start"
} ],
"icons" : {
"64" : "image1.png",
"64" : "image2.png"
},
"description": "Blah blah blah",
"manifest_version": 2,
"name": "Working Title",
"permissions": [ "activeTab", "https://www.facebook.com/*", "http://www.facebook.com/*" ],
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "1.0",
"web_accessible_resources": [ "images/*.png" ]
}
I don't know if there is something wrong with your browser or your computer, but I tested all the code onto different files and it seems to work fine. Unless there is anything clashing with the background.js from the content.js, it isn't the code that's the problem.
Icons were not the proper size of 128 x 128. Working now. Thx!
I'm trying to capture the visible area of a page using chrome.tabs.captureVisibleTab. Here is the code that makes the call:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.name == 'screenshot') {
chrome.tabs.captureVisibleTab(null, null, function(dataUrl) {
sendResponse({ screenshotUrl: dataUrl });
});
}
});
But when I try to capture the tab I get this error:
Unchecked runtime.lastError while running tabs.captureVisibleTab: The 'activeTab' permission is not in effect because this extension has not been in invoked.
Here is my manifest file:
{
"manifest_version": 2,
"name": "Empathy",
"version": "0.1",
"description": "Simulate accessibility issues for websites.",
"browser_action": {
"default_icon": "empathy19.png",
"default_title": "Empathy!"
},
"permissions": [
"activeTab",
"contextMenus",
"desktopCapture",
"tabCapture",
"tts" // Text-to-speech
],
"background": {
"scripts": [
"boot.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"src/helpers.js",
"src/colorblindness.js",
"lib/colorvision.js",
"lib/html2canvas.js"
]
}
]
}
I have active tab permissions
The call is being made from a background script
I'm matching <all_urls>
Why do I get that error?
There are things that talk about <all_urls> as something to match, but what I was missing was the <all_urls> permission. After I added the permission, it worked.
Having trouble, and wasnt finding anything else on here that answered what I have :/
Manifest:
{
"name": "Item Sniper",
"version": "1.0",
"description": "Sniper",
"browser_action": {
"default_icon": "face.png",
"default_title": "Sniper"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"notifications",
"http://*/*"
]
}
Background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null,{file: "buy.js"});
}
);
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
var notify = webkitNotifications.createNotification(
'face.png', // icon url - can be relative
'Hello!', // notification title
'Oh hellow!' // notification body text
);
});
Buy.js [There's more to it, but this is the notification part]:
chrome.extension.sendRequest({msg: "Sup?"}, function(response) { // optional callback - gets response
console.log(response.returnMsg);
});
I basically want the content script to create a notification, but I didnt know if it was possible while sticking with a js script as background :/
Thanks for any help,
Alex
The background property is only available for manifests using version 2. If you want to support this you'll need to update your manifest to the following;
{
"name": "Item Sniper",
"version": "1.0",
"description": "Sniper",
"manifest_version": 2,
"minimum_chrome_version": "18",
"browser_action": {
"default_icon": "face.png",
"default_title": "Sniper"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"notifications",
"http://*/*"
]
}
Notice that I also set the minimum_chrome_version property to 18 as manifest version 2 can only be used when targeting this version of Chrome or newer.
I think you missed to call notify.show(); in your background.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
var notify = webkitNotifications.createNotification(
'face.png', // icon url - can be relative
'Hello!', // notification title
'Oh hellow!' // notification body text
);
notify.show();
});
http://code.google.com/chrome/extensions/notifications.html#api
How would I append functions to the right click menu in the browser? E.g something appended to the right click menu which does function dosomething() which is located in my extension.
I made simple extenstion using the contextMenu API - link Hope this works well as an example.
manifest.json -
{
"manifest_version": 2,
...
...
"permissions": [
"contextMenus",
"tabs"],
...
...
"background": {
"page": "background.html",
"scripts": ["main.js"]
}
}
main.js -
searchUrbanDict = function(word){
var query = word.selectionText;
chrome.tabs.create({url: "http://www.urbandictionary.com/define.php?term=" + query});
};
chrome.contextMenus.create({
title: "Search in UrbanDictionary",
contexts:["selection"], // ContextType
onclick: searchUrbanDict // A callback function
});
For more information on different context types - link
Found out how, using the contextmenu API https://developer.chrome.com/docs/extensions/reference/contextMenus/
Anurag-Sharma's answer updated for manifest v3:
manifest.json -
{
"name": "terapeak",
"description": "easy way to research ebay products",
"version": "1.0",
"manifest_version": 3,
"permissions": [
"contextMenus",
"tabs"
],
"background": {
"service_worker": "main.js"
}
}
main.js
searchTerapeak = function(word){
var query = word.selectionText;
chrome.tabs.create({url: "https://www.ebay.com/sh/research?dayRange=365&sorting=-avgsalesprice&tabName=SOLD&keywords="
+ query}); };
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({
id: "1",
title: "Terapeak this!",
contexts:["selection"], // ContextType
}); })
chrome.contextMenus.onClicked.addListener(searchTerapeak);
Why you need to removeAll each time: Why does chrome.contextMenus create multiple entries?