- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 03-04-2021 07:10 AM
Hi all,
Welcome back to the Decoding Chrome extensions for ServiceNow Series. This is part 2 and today we will be looking into another important file, which stores the background scripts. This post is going to be a lengthy one, so let us directly dive into the topic.
You need to complete the tasks mentioned in Part 1 before proceeding forward.
Step 1) Create a new file in the directory and name it as 'background.js'
Let us understand a little deeper about this file.
Extensions are event based programs used to modify or enhance the Chrome browsing experience. Events are browser triggers, such as navigating to a new page, removing a bookmark, or closing a tab. Extensions monitor these events in their background script, then react with specified instructions.
A background page is loaded when it is needed, and unloaded when it goes idle. Some examples of events include:
- The extension is first installed or updated to a new version.
- The background page was listening for an event, and the event is dispatched.
- A content script or other extension sends a message.
- Another view in the extension, such as a popup, calls runtime.getBackgroundPage.
Once it has been loaded, a background page will stay running as long as it is performing an action, such as calling a Chrome API or issuing a network request.
Effective background scripts stay dormant until an event they are listening for fires, react with specified instructions, then unload.
Background scripts are registered in the manifest under the "background" field. In part one we had added following code to our manifest file :
"background": {
"scripts": ["jquery-3.6.0.min.js", "background.js"],
"persistent": true
}
Background scripts are listed in an array after the "scripts" key, and "persistent" should be specified as false.
The only occasion to keep a background script persistently active is if the extension uses chrome.webRequest API to block or modify network requests. The webRequest API is incompatible with non-persistent background pages.
Multiple background scripts can be registered for modularized code.
"background": {
"scripts": [
"backgroundContextMenus.js",
"backgroundOmniBox.js",
"backgroundOauth.js"
],
"persistent": false
}
Structure background scripts around events the extension depends on. Defining functionally relevant events allows background scripts to lie dormant until those events are fired and prevent the extension from missing important triggers.
Before start writing code to 'background.js', let us focus on another parameter in scripts key 'jquery-3.5.1.min.js'
Step 2) Navigate to https://jquery.com/download/ and download a Compressed copy of available jQuery files locally to our directory. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
Now our local directory will look something like this :
Now let us put some code into our background script.
Step 3) Put the below code into our background script file and save it.
chrome.contextMenus.create(
Object.assign(
{
"id": "codesnippets",
"contexts": ["editable"],
"title": "CodeIt Snippets",
},
{
"documentUrlPatterns": ["https://*.service-now.com/*"],
}
)
);
var snippets = {
"codesnippet1": [
"codesnippets",
"Encoded gr",
"var queryString = 'priority=1^ORpriority=2';\nvar now_GR = new GlideRecord('incident');\nnow_GR.addEncodedQuery(queryString);\nnow_GR.query();\nwhile (now_GR.next()) {\n gs.addInfoMessage(now_GR.getValue('number'));\n}",
],
"codesnippet2": [
"codesnippets",
"GlideAggregate",
"var count = new GlideAggregate('incident');\ncount.addEncodedQuery('active=true');\ncount.addAggregate('COUNT');\ncount.query();\nvar incidents = 0;\nif (count.next())\n incidents = count.getAggregate('COUNT');\ngs.info(incidents);",
],
};
for (var s in snippets) {
chrome.contextMenus.create(Object.assign({
"id": s,
"parentId": snippets[s][0],
"contexts": ["editable"],
"title": snippets[s][1],
"onclick": insertSnippet
},
{
"documentUrlPatterns": ["https://*.service-now.com/*"],
}));
}
function insertSnippet(e, f) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
"snippet": snippets[e.menuItemId][2]
});
});
}
Now let us understand above code :
In part one, we have written the following code in our manifest file -
"permissions": ["https://*.service-now.com/*", "contextMenus"]
You can use the chrome.contextMenus API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages.
You must declare the "contextMenus" permission in your extension's manifest to use the API.
Also, you should specify a 16x16-pixel icon for display next to your menu item.
"permissions": [
"contextMenus"
],
"icons": {
"16": "icon-bitty.png",
"48": "icon-small.png",
"128": "icon-large.png"
},
Context menu items can appear in any document (or frame within a document), even those with file:// or chrome:// URLs. To control which documents your items can appear in, specify the documentUrlPatterns field when you call the create() or update() method.
You can create as many context menu items as you need, but if more than one from your extension is visible at once, Google Chrome automatically collapses them into a single parent menu.
'create' method - Creates a new context menu item.
contexts - List of contexts this menu item will appear in. Defaults to ['page'].
documentUrlPatterns - Restricts the item to apply only to documents or frames whose URL matches one of the given patterns.
id - The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.
onclick - A function that is called back when the menu item is clicked.
parentId - The ID of a parent menu item; this makes the item a child of a previously added item.
title - The text to display in the item; this is required unless type is separator. When the context is selection, use %s within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin".
You can use the chrome.tabs API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.
'query' method - Gets all tabs that have the specified properties, or all tabs if no properties are specified.
active - Whether the tabs are active in their windows.
currentWindow - Whether the tabs are in the current window.
sendMessage - Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.
Congrats, Now you have completed two major milestones in this learning journey. In the next part, we will be creating the last file needed for our extension to work and our basic extension will be ready.
See you in the next article.
Thank you.
Vishal Ingle,
DxSherpa Technologies Pvt. Ltd., Pune.
Other Articles in the Series till Now :
Decoding Chrome Extensions for ServiceNow : Part 1 (manifest.json)
Decoding Chrome Extensions for ServiceNow : Part 2 (background.js)
Decoding Chrome Extensions for ServiceNow : Part 3 (Content Scripts)