Problem

Recently I'm learning Javascript and playing with Chrome Extension during this quarantine time, where I need chrome.storage.sync to save and retrieve some user settings.

It's a pretty easy use case that I used

var url = document.getElementById('url_regex').value;
var pattern = document.getElementById('pattern_regex').value;

chrome.storage.sync.set({url: pattern}, function() {
  console.log('Saved pattern ' + url + ' ' + pattern);
});

It feels quite natural for a person who writes Python and Java. Suppose the url is abc.com, and pattern is [a-z]+\.com. However, turned out the result will be

{url: '[a-z]+\.com'}

instead of

{'abc.com': '[a-z]+\.com'}

Wait, what?

From the result the cause is that instead of the value of url, the variable name is used. Later I learned that from ES6 there is an enhancement called Computed Property Names, to support computed names in object property definitions.

Solution

It's simple as wrapping a [] around the key variable as

chrome.storage.sync.set({[url]: pattern}, function() {
  ...
}