Open different page as defined when calling notify function in chrome extension? - javascript

In my code, I wish to be able to call the function notify each time with a different link, and the specific notification created opens a new tab with that page when clicked
Note: I'm very confused by the documentation, please don't just link me to that, I really want an explanation with an example. Thanks
This is what I have so far:
function notify(title, msg, link, callback) {
//no idea what to do with the link here
var options = {
title: title,
message: msg,
type: "basic",
iconUrl: "Icon.png"
};
return chrome.notifications.create("", options, callback);
}
And to call the function:
notify("title", "message", "http://www.example.com", function(notification) { });
which would display
Title
Message
and upon clicking, would open a new tab to http://www.example.com
then later, I would call it again with
notify("title", "message", "http://www.google.com", function(notification) { });
and that one would open a new tab to http://www.google.com when clicked
Thanks if you can help!

There is no direct support for attaching an onclick handler to a notification. Instead, if you click a notification's body, it will generate a general chrome.notification.onClicked event, providing the ID of the notification.
You will have, therefore, to maintain your own matching of IDs to URLs.
var urls = {};
chrome.notifications.onClicked.addListener(notifyClick);
chrome.notifications.onClosed.addListener(notifyClose);
function notify(title, msg, link, callback) {
var options = {
title: title,
message: msg,
type: "basic",
iconUrl: "Icon.png",
isClickable: true // New in Chrome 32, alters the appearance?
};
return chrome.notifications.create("", options, function(id) {
// New ID will be generated
urls[id] = link;
});
}
function notifyClick(id) {
// Look up the URL:
chrome.tabs.create({url: urls[id]});
// Optionally, close the notification:
// chrome.notifications.clear(id, function(){});
}
function notifyClose(id, byUser) {
// Clean up the matching
delete urls[id];
}
Please note: there is a caveat regarding closing notification programmatically. If the notification is closed from the message center, it will not immediately disappear.

Related

chorme extension - How to replace user selected text

I'm working on a translate chrome extension. I want to get the user selection and translate it after the user click on a context menu voice. I've implemented this code but not work as expected. I've tested it on instagram and seems working into the DM input field. The same code will not work as expected with facebook text input for messages or status textarea. How I can manage the selected text replacing after that it's translated?
background.js
const processSelection = (info, tab) => {
axios({
method: 'GET',
url: 'https://translate.googleapis.com/translate_a/single',
params: {
client: 'gtx',
sl: 'auto',
tl: 'en',
dt: 't',
q: info.selectionText
}
}).then( (res) => {
browser.tabs.sendMessage(tab.id, {translation: res.data[0][0][0]});
});
}
browser.contextMenus.create({
id: 'selection-translate',
title: 'Translate selection',
contexts: ['editable','selection']
});
browser.contextMenus.onClicked.addListener(processSelection);
content-script.js
browser.runtime.onMessage.addListener( (message) => {
console.log(message);
const selectedText = window.getSelection();
const range = selectedText.getRangeAt(0);
console.log(range);
// I've tried to use deleteContents() but without selecting the node it will not work
range.selectNodeContents(range.commonAncestorContainer);
range.deleteContents();
// sometimes the text is appended outside the text input/textarea if selectNodeContents isnt used
range.insertNode(document.createTextNode(message.translation));
});
Another doubt I have is about context menu. If I want to add some submenu to the main one, how I will handle the click event?I want to give the user the ability to select the destination language with other context menus, but not sure how to proceed.
Thank you for the help.

How to disable fullcalendar

I want to set authorities on my calendar. Only certain users can update the data. While all users can only see the event and are not allowed to make any changes. I'm using select function to popup modals. Can fullcalendar be disabled? I want it to be like readonly function. Which means all users can read the data. I try to do like this :
if(#ViewBag.User == "Admin")
{
editable = true,
}
But it doesn't work. The events can still be edited since I also set that attribute inside my JSON codes for events. Is there any way to solve this? Thanks
Try this,
editable = false
and set URL for the event as
url: '/Event/Create/'
if you do not want any redirection to add use below link
url: 'Javascript:'
User this URL in events section. like this
$('#calendar').fullCalendar({
editable = false,
events: [
{
title: 'My Event',
start: '2010-01-01',
url: 'http://google.com/'
},
{
title: 'My Event',
start: '2010-01-01',
url: 'Javascript:'
}
// other events here
],
eventClick: function(event) {
if (event.url) {
window.open(event.url);
return false;
}
}
});

Tinymce: How can I check if a window has been closed?

Hi I have a plugin that opens a window with a own html-page.
tinymce.PluginManager.add('ds_format_edit', function (editor, url) {
editor.addMenuItem('ds_format_edit', {
text: 'Formatvorlage anpassen...',
icon: false,
onclick: function () {
editor.execCommand("ds_format_edit");
}
});
editor.addCommand('ds_format_edit', function () {
editor.windowManager.open({
title: "Formatvorlagen anpassen ...",
url: 'DSFormatEditDialog.html',
width: 800,
height: 350,
buttons: [
{
text: 'OK',
onclick: function () {
top.tinymce.activeEditor.windowManager.close();
}
},
{ text: 'Cancel', onclick: 'cancel' }
]
}, {
tinymce_formats: getFormats(),
});
});
});
tinymce_formats is my parameter which I pass to the window. The dialog modify this parameter. All thats works.
Now I want to reintialize the tinymce editor if the window has been closed (if the user pressed the OK button) to get the modified parameter.
Is there any open callback function or an other way to realize that?
Thanks Felix
EDIT:
I call this plugin with a Button. The Plugin open a window with a parameter. In this window I do something and modify the parameter. And if the window has been closed I want to use my reintialize function. I need a function which knows when the window is closed to execute the reintialize function.
To reset everything (button state & content) you need to unload the editor and initialize it again like this way :
# Remove TinyMCE instance
tinyMCE.remove();
# Initialize TinyMCE again
tinyMCE.init({ ... });
Or, if you only need to empty the text content, use this :
tinyMCE.get('#my-textarea-id').setContent("");
To tell to your main app the window has been closed, you can fire a custom event :
{
text:'OK',
onclick: function () {
jQuery(document).trigger('myCustomCloseEvent');
top.tinymce.activeEditor.windowManager.close();
}
}
In you main app, bind the event :
jQuery(document).on("myCustomCloseEvent", function()
{
alert('Window has been closed');
});

How to call an internal javascript function from url?

I'm collecting some data from a series of similar webpages and store them in excel sheet. I'm using the opener class in urllib2 within python for this work.
The problem is that in one group of these pages, you need too click on a hyperlink so that the needed data appear.
Is there any way that I could fake the click on this hyperlink and include it in the address that I send within my python code?
This is the href tag of the link:
<a href="#" onClick="refresh_reg_table();refresh_reg_list(); return false;">
And here are the functions called in onClick:
function refresh_reg_table(order){
Ajax.Responders.register({
onCreate: function() {
$('ajax_spinner2').show();
},
onComplete: function() {
$('ajax_spinner2').hide();
}
});
new Ajax.Updater('table_registrations', 'ajax/get_table_registrations.php', {
method: 'get',
parameters: {
table: 'registrations',
idevent : 143593,
sorted : order},
evalScripts: true,
});
}
function refresh_reg_list(){
Ajax.Responders.register({
onCreate: function() {
$('ajax_spinner2').show();
},
onComplete: function() {
$('ajax_spinner2').hide();
}
});
new Ajax.Updater('reg_list', 'ajax/get_list_registrations.php', {
method: 'get',
parameters: {
type: 'table_name_reg',
idevent : 143593
},
evalScripts: true,
});
}
All you can do through the address bar is using the javascript: prefix and it would run all your JavaScript code after that javascript: prefix.
you also better change the your hyperlink like:
...
Use javascript:yourFunction() to start the page's function - i dont think there's any other way around it

Chrome Extension - Dynamic Right-Click Menu

I am trying to create an option in the right-click menu that is dynamic based on the user's action. If the user selects some text, then right-clicks, the option will say "Display It". If the user right-clicks without selecting some text, the option will say "Select Some Text First" and be grayed out. I am wondering how do I achieve this?
I currently have it so that the option will appear only when the user has selected some text. I am unsure how to modify it to meet my second requirements.
chrome.contextMenus.create ({
title:"Display It!", contexts:["selection"], onclick:function(info,tab) {
chrome.tabs.sendRequest(
tab.id,
{callFunction: "displaySidebar", info: info},
function(response) {console.log(response);}
);
}
});
You cant grey an item out...Chrome has gone to a bit of effort to only make context menu items appear when its relevant which is why i guess theres no grey out option. Your way goes against what Chrome have tried to implement and I think you really should rethink the way you go about this.
Saying that, you can use the chrome.contextMenus.update to change a menu item.
The following code is about as good as your going to get it your way (seriously, rethink this idea)....
function selectedTrueOnClick(info, tab) {
chrome.tabs.sendRequest(
tab.id, {
callFunction: "displaySidebar",
info: info
}, function(response) {
console.log(response);
});
}
function selectedFalseOnClick(info, tab) {
//
}
var contextMenuID = chrome.contextMenus.create({
title: "Select some text",
contexts: ["all"],
onclick: selectedFalseOnClick
});
function contextMenuUpdate(selected) {
if (selected) chrome.contextMenus.update(contextMenuID, {
title: 'You selected "%s"',
contexts: ["all"],
onclick: selectedTrueOnClick
});
else chrome.contextMenus.update(contextMenuID, {
title: "Select some text",
contexts: ["all"],
onclick: selectedTrueOnClick
});
}
contextMenuUpdate(false);
I was looking to accomplish the same thing as the original post, and was able to get it working using some message passing. Regardless of whether it's bad practice or not, I used the enabled(true/false) contextMenu property to leave my context menu option present, but grayed out.
I created a context menu. The important property is the id. The rest is mostly arbitrary because it will be changed dynamically.
In content.js
//This event listener will determine if the context menu should be updated
//based on if the right-button was clicked and if there is a selection or not
document.addEventListener("mousedown", function(event){
if (event.button !== 2) {
return false;
}
var selected = window.getSelection().toString();
if(event.button == 2 && selected != '') {
//get selected text and send request to bkgd page to create menu
chrome.runtime.sendMessage({
'message': 'updateContextMenu',
'selection': true});
} else {
chrome.runtime.sendMessage({
'message': 'updateContextMenu',
'selection': false});
}
}, true);
In background.js:
//add a message listener that will modify the context menu however you see fit
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message == 'updateContextMenu') {
if (request.selection) {
chrome.contextMenus.update('contextMenuId',{
'title': 'New Title',
'enabled': true,
"contexts": ["all"],
'onclick': someFunction
});
} else {
chrome.contextMenus.update('contextMenuId',{
'title': 'Select some text first',
'enabled': false,
"contexts": ["all"]
});
}
} else {
sendResponse({});
}
});
//The original context menu. The important property is the id. The rest is mostly
//arbitrary because it will be changed dynamically by the listener above.
chrome.contextMenus.create({
'id': 'contextMenuId',
'enabled': false,
'title': 'Some Title',
"contexts": ["all"]
});

Categories

Resources