Typeerror: Cannot Read Property 'sync' of Undefined
- HTML
- CSS
- JavaScript
- Bookmark Director: chrome://bookmarks.
- History: chrome://history.
- New Tab: chrome://newtab.
- Data can exist automatically synced with Chrome sync (using
storage.sync). If you are logged-in and have sync enabled, y'all can access your data on multiple devices. - Its asynchronous capability makes information technology faster than the synchronous localStorage API.
- Data can exist stored as objects compared to the localStorage API, which stores information in strings.
- Chrome storage is non encrypted, and and then y'all should non store confidential information.
- Task: the value user has entered in the input field
- Id: And id generated using
Date.now() - Complete: A boolean which marks the task as complete
- Create a reference to the
<ul></ul> - Using
document.createElement,create a new<li>element. - Using
inner.HTML, set the value of the newly created listing element to the task variable. - If the task is completed, add together the consummate course using
classList.add() - Add a dataset attribute to store the
id(nosotros will employ this to remove the item from the list)
Getting Started with Chrome Extensions
Extensions are modest software programs that customize your browsing experience. They are used to block ads and popups, format JSON, edit grammar, help with vocabulary, design, programming, among others. In a nutshell, Chrome extensions enhance the functionality of your browsing experience.
In this tutorial, you lot volition be creating a Chrome extension to track your daily tasks. With the extension enabled, every time you open a new tab, you will see the jobs yous want to keep track of for the day. You lot will exist able to add together a job, marker the task consummate, and delete it.
Prerequisites
To follow this tutorial, you will need working cognition of the following:
You will also need the Chrome web browser to install and test your extension.
Introduction to Chrome extensions
Chrome extensions consist of different components created with web development technologies: HTML, CSS, and JavaScript. These components, including groundwork scripts, content scripts, options page, and UI elements, are used as needed, depending on the extension's functionality.
Regardless of what yous are edifice, nonetheless, there is one file crucial to developing your extension: manifest.json. Every extension has this JSON-formatted file that provides essential information.
Take a moment to dissect an extension yous regularly utilise. Navigate to chrome://extensions/ to explore.
Depending on your extensions, your page will look something like this:
Right off the bat, you volition see that each extension has iii pieces of data: proper name, description, and an icon. If you click D etails on whatever given extension, y'all will see some additional data like the version, permissions needed by the extension to work, and size.
This information is what is included in a manifest file. Some of these data points are required, and others are optional.
Each manifest has can comprise several fields, iii of which are required:
| Field | JSON | Type | Description | Required |
|---|---|---|---|---|
| Manifest Version | manifest_version | number | It is an integer specifying the version of the manifest specification of your package. As of Chrome eighteen, developers should utilise two. | truthful |
| Proper name | proper noun | string | With a maximum of 45 characters, this field identifies your extension. | true |
| Version | version | cord | This field of one to four dot-separated integers identifies the version of your extension | true |
| Description | description | string | Capped at 132 characters, this plain text cord describes your extension | false |
| Icon | icons | object | Icons represent your extension | false |
Create the manifest file for your Chrome extension
Create a new directory, taskTracker, and in it, create a file called manifest.json. Copy and paste the following lines in your manifest.json:
{ "manifest_version" : 2, "proper name" : "Chore Tracker", "version" : "1.0.0", "description": "Extension to proceed track of our tasks", "icons" : { "16": "icons/task16.png", "48": "icons/task48.png", "128" : "icons/task128.png" } } Each Chrome extension can have icons of different sizes, every bit shown in the lawmaking above. Co-ordinate to the documentation, you should always offer a 128px x 128px icon; it's used during installation and by the Chrome Spider web Shop. The documentation recommends providing a 48px x 48px icon for utilize on the extension management folio. Yous tin also specify a 16px ten 16px icon to use as a favicon.
Create an icons folder in your root directory and save the icons at that place. You can create your ain icons or download them from iconfinder.com. I downloaded three icons and named them with respect to their size. For example, I've named the icon of size 16px every bit task/16.png.
Install your Chrome extension in Developer mode
Navigate to chrome://extensions/, and turn on developer mode past using the toggle on the height right of the screen. Once you turn on developer mode, you lot volition run into three buttons at the top: Load unpacked, Pack extension, and Update.
Click on Load unpacked and select your extension'southward directory, taskTracker, from the file picker. Make certain your manifest.json lives at the root of your directory. Once selected, you will see your Job Tracker extension with the version and the description.
Depending on your settings, you may or may not encounter the extension in your toolbar. If you don't see your extension, click on the jigsaw icon, find your extension and pin it.
And, there, you lot have installed your starting time extension. The extension doesn't do annihilation yet. Your next stride will be to give it some instructions.
Build the Chore Tracker extension
Override the default new tab page
With this extension, every time you open a new tab y'all'll exist able to see your tasks for the day. This extension will override Google'south default new tab folio, which displays the most used websites.
At that place are three pages an extension can replace:
Chrome extension uses the chrome_url_overrides cardinal to override the new tab page. The value of this key is another object that tin can include a cardinal of bookmarks, history or newtab and the value will be an HTML file (in this example, it is called index.html, though it can be named anything). For this project, you lot will exist replacing the New Tab.
{ "manifest_version" : 2, "name" : "Task Tracker", "version" : "i", "clarification" : "Extension to go along track of your tasks", "icons" : { "16": "icons/task16.png", "48": "icons/task48.png", "128" : "icons/task128.png" }, "chrome_url_overrides" : { "newtab": "index.html" } } Test out the page override. Create an index.html file in the root directory of your extension, and add the following content to information technology:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=i.0" /> <title>Task Tracker</title> </style> </caput> <trunk> <h1> Job Tracker </h1> </body> </html> Click the refresh icon on the extension and open a new tab. A popup volition appear from the browser confirming the changes task tracker has made. You could either go along the changes past selecting Proceed it button or discard the changes by selecting Alter it back.
You will select Keep it to come across a blank page with a header Chore Tracker.
Add the HTML and CSS for the Chore Tracker
For this extension, yous demand two things on our page: a course that adds tasks and a <div> element that displays those newly added tasks. This HTML will exist added inside the index.html file. Copy and paste the highlighted lines into index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-viii" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Job Tracker</title> <link href="styles.css" rel="stylesheet" /> </head> <body> <div class="container"> <div id="chief"> <div id="formContainer"> <form id="tasksForm"> <div> <label>What tasks would you lot like to runway today?</characterization> <input type="text" aria-describedby="tasks" id="tasks" /> <button blazon="submit" id="addTask"> Add Task </push button> </div> </form> </div> <div id="listContainer"> <ul id="tasksList"></ul> </div> </div> </div> </torso> </html> Create a new file called styles.css at the root directory of your project, and copy and paste the post-obit styles inside:
html, body { top: 99%; background-colour: #a1cbcf; colour: #231F20; } .container { height: 100%; min-height: 100%; display: flex; flex-direction: cavalcade; align-items: center; justify-content: center; } #principal { width: 65%; display: flex; } #formContainer { width: 33%; margin-right: 20rem; } #tasksForm { display: block; } #listContainer { max-height: 500px; border: none; width: xl%; } #tasksList { list-style: none; } #tasksList li { pinnacle: 30px; padding-left: 15px; line-superlative: 2; border: 1px solid snow; margin-bottom: 8px; box-shadow: 1px 1px; font-size: 0.9rem; } .consummate { background-color: #e9c686; color: rgb(255, 255, 255); text-decoration: line-through; } button { background-color: #e9a830; tiptop: 25px; color: white; width: 80px; padding: 3px; edge: 1px solid snowfall; } label { font-size: one.6em; font-weight: 500; display: block; margin-bottom: 1em; } input { width: 75%; height: 22px; } span { float: right; margin-right: 12px; } Refresh your Task Tracker page to meet the changes you made. You will run into a label, an input field, and a button. Since you haven't added whatever tasks yet, the list container is not visible.
An introduction to Chrome's local storage API
Y'all won't be setting up a database for this extension; instead, you will be using Chrome's storage API to store, remember, and rail changes to user data.
Some cardinal features to know about the chrome storage API:
You can learn more most the key differences betwixt the Web Storage API and Chrome Storage in an article on DEV chosen Chrome Local Storage in Extensions.
You tin can employ Chrome'southward Developer Tools to encounter how storing, retrieving, and removing data from Chrome sync works.
Right click on a new tab, and click Audit. A window will appear at the lesser of the browser, then select Console tab. In your console, run the following script to store an instance array of tasks:
chrome.storage.sync.fix({ task: ['create an extension', 'drink a glass of water'] }) Running this command would have given you the post-obit fault: Uncaught TypeError: Cannot read property 'sync' of undefined at <anonymous>.
This fault occurs considering you lot haven't defined permissions yet. To utilize most chrome APIs, your extension must declare its intent in the permissions field of the manifest. This helps limit damage in case your app is compromised. For your extension, you will declare the storage permission.
Update your manifest.json file to add "permissions": ["storage"] at the bottom:
{ "manifest_version" : two, "name" : "Task Tracker", "version" : "1", "description" : "Extension to proceed track of your tasks", "icons" : { "16": "icons/task16.png", "48": "icons/task48.png", "128" : "icons/task128.png" }, "chrome_url_overrides" : { "newtab": "index.html" }, "permissions": ["storage"] } Navigate to chrome://extensions and reload the extension. Now when you open a new tab and call the gear up() method, it will work.
Now that y'all have stored information, you can retrieve it.
Run the post-obit script in the console:
chrome.storage.sync.become('task', part(items) { console.log(items) }); The event will be an object with one fundamental: task, whose value is the assortment of 2 tasks that you added but a moment ago.
You only accept i key stored in your storage. If you have multiple keys and you want to run across all of them, yous can run the same script as before, but replace the chore fundamental with null.
chrome.storage.sync.get(null, function (items) { panel.log(items) }); And to delete a cardinal from storage:
chrome.storage.sync.remove("job"); If yous remember the data using the get() method now, you volition get an empty object. Removing the task key removed the entire array of tasks. But what if y'all wanted to remove just the showtime chemical element?
In that case, you can get the chore assortment using the get() method, manipulate the assortment every bit needed, and so update the stored value using the gear up() method.
Running the following code will result in i chemical element in our task array:
chrome.storage.sync.get({task: []}, items => { items.chore.splice(0, one); chrome.storage.sync.gear up(task: items, function() { console.log('Item deleted!'); }); }) Implement local storage in Chore Tracker
Apply what you've learned to the Task Tracker extension.
Create a new file called app.js in the root directory of your projection, and load this file before the closing trunk tag in index.html.
<body> <div class="container"> ... </div> <script src="app.js"></script> </body> In app.js, permit's check if the task listing exists. If it exists, you will evidence the items in the list; if it doesn't exist, you will create one.
//bank check if the listing exists chrome.storage.sync.go("tasks", function (result) { if (result.tasks) { issue.tasks.map((task) => { console.log(task) }); } else { chrome.storage.sync.set({ tasks: [] }); } }); The outset time you load the extension, information technology will create and store an empty array called tasks in your storage. If you open dev tools and run the following script, you will see an empty array:
chrome.storage.sync.get(null, function (items) { console.log(items) }); Create an event handler at the top of the page for your button:
const addTask = document.querySelector("#addTask"); addTask.addEventListener("click", e => { e.preventDefault(); let task = document.querySelector("#tasks").value; if (!task.length) { alert("Delight add a task to add"); } else { const obj = { task: task, consummate: false, id: Engagement.now(), }; chrome.storage.sync.become("tasks", role (effect) { if (result.tasks) { chrome.storage.sync.set({ tasks: [...result.tasks, obj] }); } }); document.querySelector("#tasks").value = ""; } }); Using the document method querySelector(), in the code above you are selecting the Add Task push and attaching the click issue listener.
e.preventDefault() is used to cancel the default action when the course is submitted.
Next, you will store the value of the input in a variable called task. You don't want the user to submit an empty job. When the user submits the task, you will remove whitespace from both sides of the input using the trim() method. If the length of the trimmed input is 0, you will alert the user it's empty. If it's non empty, you will create a new object with the post-obit key:value pairs:
Using Chrome's set() and get() methods, you lot tin so update your tasks array. Lastly, you clear the input field.
Rendering changes to the chore list on the UI
Refresh the extension, open a new tab, and add a chore. Aught will happen on the UI. But if you open dev tools and run the post-obit script, you volition meet that your task has been stored.
chrome.storage.sync.become(zip, part (items) { panel.log(items) }) But you want to be able to see the chore as soon every bit you've hit submit. To do this, copy and paste the post-obit code at the summit of app.js:
addTasktoTheList = (job) => { const ul = document.querySelector("#tasksList"); const li = certificate.createElement("li"); li.innerHTML = task.task; job.complete ? li.classList.add("consummate") : ""; li.dataset.id = task.id; var span = certificate.createElement("span"); bridge.setAttribute("id", "remove"); span.innerHTML = "Ten"; li.append(span); ul.append(li); }; When the user adds a job, you lot desire to do the following things:
Yous are also creating a <bridge> for deleting the tasks. In the end, you will append the <span> to the <li>, and the <li> to the <ul> tag.
At the end of your callback function for addEventListener, call addTasktoTheList(obj) and pass in the object yous created.
If you add together a chore now, you lot will see the job displayed on the screen. If you lot open a new tab, you won't encounter the job displayed considering so far the code is only printing the job to the console and does not show it on the UI. You lot'll modify that next.
In the part where you check whether the tasks assortment exists or not, supervene upon the line console.log(task); with addTasktoTheList(task);. At present, when yous open up a new tab (or refresh the tab yous are on), y'all will come across the listing of tasks.
Next, add together two functions where the user can marking the task as consummate and remove it. First, in your addTasktoTheList() part, correct before you append the <li> tag, add two more than event listeners:
addTasktoTheList = (job) => { const ul = document.querySelector("#tasksList"); const li = document.createElement("li"); li.innerHTML = task.chore; task.complete ? li.classList.add together("consummate") : ""; li.dataset.id = task.id; var span = document.createElement("span"); bridge.setAttribute("id", "remove"); span.innerHTML = "X"; li.append(span); li.addEventListener("click", () => updateComplete(li), "false"); bridge.addEventListener("click", () => removeItem(li)); ul.suspend(li); }; Now, copy and paste the following code right after addTaskToTheList() to add the removeItem() office:
const removeItem = (e) => { due east.parentNode.removeChild(e); const dataId = e.dataset.id; chrome.storage.sync.go({ tasks: [] }, function (items) { const updatedList = items.tasks.filter((item) => item.id != dataId); chrome.storage.sync.set({ tasks: updatedList }); }); }; For removing the particular from the DOM, y'all will utilize the Node.removeChild() method. Just that's not enough; y'all have to remove the item from both the DOM and the storage.
You will use the object's id value to select the particular, filter, and update the task array.
Yous will do something similar for toggling the consummate grade. Copy and paste this code below the removeItem() office.
const updateComplete = (e) => { if (east.tagName === "LI") { eastward.classList.toggle("complete"); const dataId = e.dataset.id; chrome.storage.sync.become("tasks", part (items) { const updatedList = items.tasks.map((particular) => { if (item.id === dataId) { item["complete"] = !item["consummate"]; } return particular; }); chrome.storage.sync.set({ tasks: updatedList }); }); } }; And that's information technology. If you open a new tab, you should exist able to add, see, remove, and mark the tasks equally consummate.
Conclusion
Overriding a tab is ane mode to use chrome extension. You can update the DOM of the current page (replace all the images with kittens or change the background colour) or aggrandize this extension past using different APIs. If you are interested in the atmospheric condition or want to learn a new word, you can apply APIs in a chrome extension to heighten your feel.
Y'all could also apply Twilio's SMS API to add tasks to your extension from anywhere. Or utilise Twilio's SMS API to send yous reminders.
Shajia Abidi is a full-stack web developer with a focus on forepart-end developme northward t. When non coding, she is either writing or reading books.
Related Posts
GSAPとVue 3でアニメーションを作成する方法
Mar 03, 2022
Greenish Sock Blitheness Platform(GSAP)は、高性能にも関わらず、手軽に使えるJavaScriptのアニメーションツールです。Vue 3とGSAPを使って、アニメーションを作成する方法をご紹介します。
Build an Electronic mail Newsletter Application with Express, Node.js and SendGrid
Mar 02, 2022
Learn how to build a full-stack app that allows users to sign up, confirm, and unsubscribe to a newsletter, and allows file uploads to send newsletters out to the masses through SendGrid contact lists.
Build a Serverless Video Chat Application with JavaScript and Twilio Programmable Video
Mar 02, 2022
Larn how to build a video calling awarding and deploy it to the Twilio Serverless platform.
How to Make a Wordle Solver with Twilio Serverless, Studio, and SMS
Feb 23, 2022
Sende und empfange SMS mit Twilio und dem SAP Cloud Awarding Programming Model
Feb 23, 2022
Node.jsからExpressへファイルのアップロードを処理する方法
Feb 22, 2022
Node.jsからExpressへファイルをアップロードする方法をご紹介します。
Typeerror: Cannot Read Property 'sync' of Undefined
Source: https://www.twilio.com/blog/getting-started-chrome-extensions
0 Response to "Typeerror: Cannot Read Property 'sync' of Undefined"
Post a Comment