I have created a Chrome extension which upon selecting text, offers a context menu link to Salesforce using the selected text:
function doSearch (search_target, tab)
{
chrome.tabs.create( {
url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
selected : true,
index : tab.index + 1
} );
}
function selectionHandler (info, tab)
{
doSearch( info.selectionText, tab );
}
function resetContextMenus ()
{
chrome.contextMenus.removeAll(
function()
{
var id = chrome.contextMenus.create( {
title: "Open in Salesforce",
contexts: [ "selection" ],
onclick: selectionHandler
} );
}
);
}
resetContextMenus();
The intention here is to mark ticket numbers and open them in SF quickly, and it works perfectly.
However, I was wondering if it's possible to update an open salesforce tab instead of launching a new one every time.
I have tried looking around and encountered the following sample extension:
https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/tabs/inspector/
But it doesn't seem to work at all (perhaps because it's outdated).
I would much appreciate any help/guidance on how to approach this.
Yes, you can do that, you can do it using the chrome.tabs.update(..) function, here is an example, this will update the tab in which your context menu item was clicked:
function selectionHandler (info, tab) {
chrome.tabs.update(tab.id, {
url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+info.selectionText.replace(/\D/g,''),
active : true
});
}
If you want to first create a new tab and then keep updating it, you can use something like this:
let tabId = -1;
function doSearch (search_target, tab)
{
const tabDetails = {
url : "https://my.salesforce.com/apex/BR_caseRedirectDependingLicense?number="+search_target.replace(/\D/g,''),
active : true,
index : tab.index + 1
};
if (tabId == -1) {
chrome.tabs.create(tabDetails, tab => {
tabId = tab.id;
});
} else {
// check if tab is still around
chrome.tabs.get(tabId, (tab) => {
if (tab) {
chrome.tabs.update(tab.id, tabDetails);
} else {
chrome.tabs.create(tabDetails, tab => {
tabId = tab.id;
});
}
});
}
}
Here is the chrome.tabs API documentation beside this two examples, you may also want to look into chrome.tabs.query(..), you can use that to find a specific tab.`
Also, in all these examples I've used active instead of selected because selected is deprecated.
Related
I tried the following code. It basically takes a screenshot from all tabs open in the current window:
function captureWindowTabs(windowId, callbackWithDataUrlArray) {
var dataUrlArray = [];
// get all tabs in the window
chrome.windows.get(windowId, { populate: true }, function(windowObj) {
var tabArray = windowObj.tabs;
// find the tab selected at first
for(var i = 0; i < tabArray.length; ++i) {
if(tabArray[i].active) {
var currentTab = tabArray[i];
break;
}
}
// recursive function that captures the tab and switches to the next
var photoTab = function(i) {
chrome.tabs.update(tabArray[i].id, { active: true }, function() {
chrome.tabs.captureVisibleTab(windowId, { format: "png" }, function(dataUrl) {
// add data URL to array
dataUrlArray.push({ tabId:tabArray[i].id, dataUrl: dataUrl });
// switch to the next tab if there is one
if(tabArray[i+1]) {
photoTab(i+1);
}
else {
// if no more tabs, return to the original tab and fire callback
chrome.tabs.update(currentTab.id, { active: true }, function() {
callbackWithDataUrlArray(dataUrlArray);
});
}
});
});
};
photoTab(0);
});
}
When I call this code from popup.html opened as a webpage, it works as expected (I trigger this from a button click in the popup.html). When I call it from the browser extension, it just gets interrupted from the first tab it selects. Any idea why that is? I can't share errors, since the debugger gets closed when called from the extension.
Supplementary, is there a way to achieve desired result without needing the visual tab switching?
While updating the next tab as active tab. make sure current tab is no more active tab by doing
chrome.tabs.update(tabArray[i-1].id, { active: false }, ()=>{});
Moving the extension to a background script fixed the problem.
Reasoning is that the popup will close once the tab switches. Hence it is required to run in the background where it is not interrupted when the popup closes.
First of all, sorry for my english, but I try my best) I have no idea whats wrong with my chrome extension. In background script I create some notifications with action by click on it. Action - open new tab with some link. When I click on the notification at first time - everything is ok, but if I click on the second notification, script open 2 different tabs with first link and with second link. The same situation with 3rd, 4th, 5th .... notification: in the next time script open +1 previous link.
There is a responsible fragment of source code:
var myNotificationID = null;
chrome.notifications.create(
'name-for-notification', {
type: 'basic',
iconUrl: 'yes.png',
title: "CONTENT WAS PUBLISHED",
requireInteraction: true,
message: "Link: " + urlchk,
buttons: [{
title: "GOT IT!"
}]
},
function(id) {
myNotificationID = id;
}
);
//
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (notifId === myNotificationID) {
if (btnIdx === 0) {
chrome.notifications.clear(notifId);
}
}
});
chrome.notifications.onClicked.addListener(function(notifId) {
if (notifId === myNotificationID) {
chrome.tabs.create({
active: true,
url: urlchk
});
chrome.notifications.clear(notifId)
}
});
I feel I need to clear smth but I don't know what exactly. Thank you for any suggestion.
For example if someone is on google.com I need to popup a different page and if someone is on xyz.com I need to pop a different page. Is that possible?
As suggested by wOxxOm, it may be a better solution to have a single popup page with several sections, and hide/show them as appropriate.
Start with all hidden, and at runtime make a decision:
document.addEventListener("DOMContentLoaded", function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// Note: this requires "activeTab" permission to access the URL
if(/* condition on tabs[0].url */) {
/* Adapt UI for condition 1 */
} else if (/* ... */) {
/* Adapt UI for condition 2 */
}
});
});
Do note that it's recommended to use Page Actions instead of Browser Actions for things that make sense only on certain pages.
In your background page you can change the page to display in popup.
Use tabs events to get selected tab and current tab url.
Use :
// Update popup url method
var updatePopupURLForSelectedTab = function (selectedTab) {
var popUpURL = DEFAULT_URL_OF_YOUR_HTML_FILE;
var selectedTabURL = selectedTab.url;
if (selectedTabURL.match(/.*\.?google\.com.*/) != null ) {
popUpURL = GOOGLE_URL_OF_YOUR_HTML_FILE;
}
else if (selectedTabURL.match(/.*\.?xyz\.com.*/) != null) {
popUpURL = XYZ_URL_OF_YOUR_HTML_FILE;
}
// Set Popup URL
chrome.browserAction.setPopup({
popup :popUpURL
});
};
// Get current selected Tab
chrome.tabs.getSelected(null, function (tab) {
updatePopupURLForSelectedTab(tab);
});
// Listen for selected tab
chrome.tabs.onActiveChanged.addListener(function(tabId, selectInfo) {
// Get selected tab
chrome.tabs.get(tabId, function (tab) {
updatePopupURLForSelectedTab(tab);
});
});
// Listen navigation update
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
updatePopupURLForSelectedTab(tab);
});
// Listen for window change
chrome.windows.onFocusChanged.addListener(function (windowId) {
chrome.tabs.getSelected(windowId, function (tab) {
updatePopupURLForSelectedTab(tab);
});
});
I am working on a chrome extension ,this extension have 2 icons in the browser action (On & Off) ;
basically when it is On the background execute the script.js (Inject the file:script.js)
using the chrome.tabs.executeScript(tab.id,{file:"script.js",function(){});
I had problems to turn it off !
I have tried to use messages communication between the background.js and the script.js but this does not work neither .
If I understand correctly, your extension should have two states, On and Off. Clicking the extension icon toggles it on/off.
In this case you should use storage so the extension knows what state it is in. So on a click event, use something like:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.storage.sync.get('state', function(data) {
if (data.state === 'on') {
chrome.storage.sync.set({state: 'off'});
//do something, removing the script or whatever
} else {
chrome.storage.sync.set({state: 'on'});
//inject your script
}
});
});
Note though that this is happening at the extension/browser level and will apply to all tabs, so you may need something more complex that records both the tab ID and the state.
You then have the choice to either always run a content script and check the on/off state before performing some action, or inject and remove the script. I'm not sure if you remove a script though. Depending on what the script does, you may just want to refresh the page (i.e. if your script messes with the DOM and you want to undo that when turning the extension off).
background.js
var enable=false;
chrome.browserAction.onClicked.addListener(function (tab) {
enable = enable ? false : true;
if(enable){
//turn on...
chrome.browserAction.setIcon({ path: 'icon.png' });
chrome.browserAction.setBadgeText({ text: 'ON' });
chrome.tabs.executeScript(null, { file: 'content.js' });
}else{
//turn off...
chrome.browserAction.setIcon({ path: 'disable.png'});
chrome.browserAction.setBadgeText({ text: '' });
}
});
To add onto what #david-gilbertson stated for making it active and inactive for certain tabs, I have created that functionality here. I also took added some functions for removing and adding tabs to the array. Enjoy!
function addTab(array, new_tab_id)
{
array.push(new_tab_id);
//then call the set to update with modified value
chrome.storage.sync.set({
active_tabs:array
}, function() {
console.log("added tab");
});
}
function removeTab(array, rem_tab_id)
{
const index = array.indexOf(rem_tab_id);
if (index > -1) {
array.splice(index, 1);
}
//then call the set to update with modified value
chrome.storage.sync.set({
active_tabs:array
}, function() {
console.log("removed tab");
});
}
chrome.browserAction.onClicked.addListener(function (tab) {`enter code here`
chrome.storage.sync.get({active_tabs : []}, function(data) {
if (data.active_tabs.includes(request.tab_id)) {
removeTab(data.active_tabs, request.tab_id)
console.log("Turned Off ".concat(request.tab_id))
document.removeEventListener("mousemove", highlightCurrentHover, false);
} else {
addTab(data.active_tabs, request.tab_id)
console.log("Turned On ".concat(request.tab_id))
document.addEventListener('mousemove', highlightCurrentHover, false);
}
});
);
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
})