Simple browserAction explanation please - javascript

I'm developing a Chrome extension which sends the highlighted selection to a speech engine API. I want to implement both context menu and on icon click. Here's the problem:
This works perfectly:
chrome.contextMenus.create({
"title" : "Speak Me",
"contexts" : ["selection"],
onclick: function (info, tab) {
speakMe(info.selectionText);
}
});
Directly underneath it I have:
chrome.browserAction.onClicked.addListener(function() {
speakMe(info.selectionText);
});
Which doesn't work.
If I leave the parameter empty it returns an audio saying "Undefined". So I guess the speech engine is telling me it got no text. What am I doing wrong?
This is the function in question, placed above:
var speakMe = function (text) {
var key, lang, url, audio;
key = "key=12345678910";
lang = "sv_se";
url = "http://tts.engine.com/api/speak?" + key + "&lang=en_us&voice=male1&speed=100&audioformat=ogg&oggbitrate=100&text=" + text;
audio = new Audio(url);
audio.play();
};
The selection text comes from another JS file:
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
But since the context menu works perfectly, I don't think there's a problem with that. It's just the browserAction that I don't get how to use properly.

Because the browser action's onClicked event doesn't have any information about the selected text. You need to figure it out yourself. You can inject a content script into the current page and get the selected text with window.getSelection().toString(). Then send the message back to the extension and speak the text.
Here's an example:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,
{code: 'window.getSelection().toString()'}, function(results) {
alert(results[0]);
});
});
It just shows an alert, but it's very easy to change it to call speakMe.

Related

How to access the correct element on mouseover with javascript (chrome extension)

I'm writing a program for a chrome extension that can return the url of a moused-over link from google search results. Right now I am able to log the urls of tags, but not header tags, which most of the results appear as. The timeout call just delays the console log (irrelevant). When I inspect the google search results, the results show that they are blocks, which I assume contain tags embedded in them. How can I access the urls from these blocks?
My existing code that works on elements:
...
document.addEventListener("mouseover", function(e){
console.log("hello")
if (e.srcElement.href != null)
{
var urlcheck = e.srcElement.href
hoverTimeout = setTimeout(function () {
console.log(urlcheck);
}, 1000);
} } )
...
srcElement is deprecated, so changed to target.
document.addEventListener("mouseover", function (e) {
if (e.target.tagName != "DIV") return;
if (e.target.className != "yuRUbf") return;
const a = e.target.getElementsByTagName("a");
console.log(a[0].href);
});

JavaScript: windoiw.location.href

I'm making a Chrome Exntesion and I'm wondering if I can have a predefined vaule to mathc the URL window.location.href
Currently my code looks like this;
chrome.tabs.getSelected(null, function(tab) {
if(window.location.href.indexOf("google") > -1) {
alert("This website is google");
} else {
alert("This website is not google");
}
However, it display it as not being google. Now I know that -1 if removed it always come up saying the website is google however, I'm not sure how to get round that.
Thanks,
Here is how to get a list of tabs that contains "google" in their url
chrome.tabs.query({}, (tabs) => {
var googleTabs = tabs.filter(tab => tab.url.indexOf("google") > -1);
// do logic on googleTabs which is of type Tab[]. link:
// https://developer.chrome.com/extensions/tabs#type-Tab
});
if you are just looking for the current tab you can use: https://developer.chrome.com/extensions/tabs#method-getCurrent

Show hidden div in page after clicking link to open the page

I have an HTML page in which a hidden div becomes visible when a button is clicked. Something like this:
$('#display').click(function(){
$('#itemList').removeClass('hide');
...
})
On another page, there is a link which when clicked takes the user back to the earlier page, and the element with id='itemList' on that page has to become visible. The code is something like this:
<a href='firstHTML.php'> View items</a>
I am not sure what else to add to the code to make the other page appear with the previously hidden element visible. Can somebody help please?
One of the most probable solution is localStorage .Where as you may also implement Cookies or string query to pass value to other page.
I am showing the use of localstorage , you may store the id in localStorage on click of anchor as below
<a href='firstHTML.php' data-showId='itemList'> View items</a>
Now bind event on anchor
$("[data-showId]").bind('click',function(){
var idToShow=$(this).attr('data-showId');
if(idToShow)
store('visibleId', idToShow);
});
Now all you need to define these functions .
function setup() {
var tmp = get('visibleId');
if (tmp)
showDiv(tmp);
}
function showDiv(cls) {
$("#"+cls).removeClass('hide');
}
function get(name) {
if (typeof (Storage) !== "undefined") {
return localStorage.getItem(name);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
function store(name, val) {
if (typeof (Storage) !== "undefined") {
localStorage.setItem(name, val);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
Now call setup() on dom ready..
First of all, I would use the jQuery function to hide/show the List instead of using an own CSS class for it:
$('#display').click(function(){
$('#itemList').show();
...
})
Then a possible approach for your problem could be to use a get Parameter for this, for example:
<a href='firstHTML.php?list=show'> View items</a>
And with jQuery
Create a helperfunction (Taken from Get url parameter jquery Or How to Get Query String Values In js):
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}else{
return results[1] || 0;
}
}
Read out the property:
var listStatus = $.urlParam('list');
Unhide the list in case it should be shown:
$( document ).ready(function() {
if(listStatus == 'show') {
$('#itemList').show();
}
});

Why doesn't this code get the URL from Safari?

I am creating a safari extension. When the user right-clicks on a link in safari, it should bring up the context menu. When the user clicks on "Get URL", it should open the clicked on url in a new window. I can't figure out how to get the url! It always opens "not found" instead.
injected.js :
document.addEventListener('contextmenu', handleContextMenu, false);
function handleContextMenu(event)
{
var target = event.target;
while(target != null && target.nodeType == Node.ELEMENT_NODE && target.nodeName.toLowerCase() != "a")
{
target = target.parentNode;
}
if(target.href)
{
safari.self.tab.setContextMenuEventUserInfo(event, target.href);
}
else
{
var foo = "href not found";
safari.self.tab.setContextMenuEventUserInfo(event, foo);
}
}
Global.html:
<!DOCTYPE HTML>
<script>
var lastUrl;
safari.application.addEventListener("contextmenu",handleContextMenu,false);
safari.application.addEventListener('command', handleCommand, false);
function handleContextMenu(event)
{
var query = event.userInfo;
lastUrl = query;
event.contextMenu.appendContextMenuItem("getUrl", "Get URL");
}
function handleCommand(event)
{
if(event.command === 'getUrl')
{
if (lastUrl)
{
safari.application.openBrowserWindow().activeTab.url = lastUrl;
}
else
{
safari.application.openBrowserWindow().activeTab.url = "not found";
}
}
}
</script>
How do I get the url? It always opens "not found" instead.
Why not just have var last url = event.userInfo in the handleCommand function? The userInfo should be defined at that point, and it should be more predictable that trying to set the value on the contextmenu event.
I don't understand why your code is not working, but there are a couple of things you might want to change anyway.
First, in the injected content script, if there's no target.href, don't bother calling safari.self.tab.setContextMenuEventUserInfo.
Second, in the global script, change your handleContextMenu function as follows:
function handleContextMenu(event) {
if (event.userInfo) {
event.contextMenu.appendContextMenuItem("getUrl", "Get URL");
}
}
That way, if the user didn't right-click a link, the context menu item won't be inserted.
Third, as Matt said, you don't need the lastUrl global variable, unless it serves some other purpose. You can refer to event.userInfo directly in handleCommand. And you don't need to check whether it's empty, because the context menu will only be inserted by handleContextMenu if it's not.
function handleCommand(event) {
if (event.command === 'getUrl') {
safari.application.openBrowserWindow().activeTab.url = event.userInfo;
}
}
Hope this helps.

Dynamic extension context menu that depends on selected text

I am trying to create entries on the Chrome context menu based on what is selected.
I found several questions about this on Stackoverflow, and for all of them the answer is: use a content script with a "mousedown" listener that looks at the current selection and creates the Context Menu.
I implemented this, but it does not always work. Sometimes all the log messages say that the context menu was modified as I wanted, but the context menu that appears is not updated.
Based on this I suspected it was a race condition: sometimes chrome starts rendering the context menu before the code ran completely.
I tried adding a eventListener to "contextmenu" and "mouseup". The later triggers when the user selects the text with the mouse, so it changes the contextmenu much before it appears (even seconds). Even with this technique, I still see the same error happening!
This happens very often in Chrome 22.0.1229.94 (Mac), occasionally in Chromium 20.0.1132.47 (linux) and it did not happen in 2 minutes trying on Windows (Chrome 22.0.1229.94).
What is happening exactly? How can I fix that? Is there any other workaround?
Here is a simplified version of my code (not so simple because I am keeping the log messages):
manifest.json:
{
"name": "Test",
"version": "0.1",
"permissions": ["contextMenus"],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"]
}],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
content_script.js
function loadContextMenu() {
var selection = window.getSelection().toString().trim();
chrome.extension.sendMessage({request: 'loadContextMenu', selection: selection}, function (response) {
console.log('sendMessage callback');
});
}
document.addEventListener('mousedown', function(event){
if (event.button == 2) {
loadContextMenu();
}
}, true);
background.js
function SelectionType(str) {
if (str.match("^[0-9]+$"))
return "number";
else if (str.match("^[a-z]+$"))
return "lowercase string";
else
return "other";
}
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
console.log("msg.request = " + msg.request);
if (msg.request == "loadContextMenu") {
var type = SelectionType(msg.selection);
console.log("selection = " + msg.selection + ", type = " + type);
if (type == "number" || type == "lowercase string") {
console.log("Creating context menu with title = " + type);
chrome.contextMenus.removeAll(function() {
console.log("contextMenus.removeAll callback");
chrome.contextMenus.create(
{"title": type,
"contexts": ["selection"],
"onclick": function(info, tab) {alert(1);}},
function() {
console.log("ContextMenu.create callback! Error? " + chrome.extension.lastError);});
});
} else {
console.log("Removing context menu")
chrome.contextMenus.removeAll(function() {
console.log("contextMenus.removeAll callback");
});
}
console.log("handling message 'loadContextMenu' done.");
}
sendResponse({});
});
The contextMenus API is used to define context menu entries. It does not need to be called right before a context menu is opened. So, instead of creating the entries on the contextmenu event, use the selectionchange event to continuously update the contextmenu entry.
I will show a simple example which just displays the selected text in the context menu entry, to show that the entries are synchronized well.
Use this content script:
document.addEventListener('selectionchange', function() {
var selection = window.getSelection().toString().trim();
chrome.runtime.sendMessage({
request: 'updateContextMenu',
selection: selection
});
});
At the background, we're going to create the contextmenu entry only once. After that, we update the contextmenu item (using the ID which we get from chrome.contextMenus.create).
When the selection is empty, we remove the context menu entry if needed.
// ID to manage the context menu entry
var cmid;
var cm_clickHandler = function(clickData, tab) {
alert('Selected ' + clickData.selectionText + ' in ' + tab.url);
};
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.request === 'updateContextMenu') {
var type = msg.selection;
if (type == '') {
// Remove the context menu entry
if (cmid != null) {
chrome.contextMenus.remove(cmid);
cmid = null; // Invalidate entry now to avoid race conditions
} // else: No contextmenu ID, so nothing to remove
} else { // Add/update context menu entry
var options = {
title: type,
contexts: ['selection'],
onclick: cm_clickHandler
};
if (cmid != null) {
chrome.contextMenus.update(cmid, options);
} else {
// Create new menu, and remember the ID
cmid = chrome.contextMenus.create(options);
}
}
}
});
To keep this example simple, I assumed that there's only one context menu entry. If you want to support more entries, create an array or hash to store the IDs.
Tips
Optimization - To reduce the number of chrome.contextMenus API calls, cache the relevant values of the parameters. Then, use a simple === comparison to check whether the contextMenu item need to be created/updated.
Debugging - All chrome.contextMenus methods are asynchronous. To debug your code, pass a callback function to the .create, .remove or .update methods.
MDN doc for menus.create(), 'title' param
You can use "%s" in the string. If you do this in a menu item, and some text is selected in the page when the menu is shown, then the selected text will be interpolated into the title.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/create
Thus
browser.contextMenus.create({
id: 'menu-search',
title: "Search '%s'", // selected text as %s
contexts: ['selection'], // show only if selection exist
})

Categories