开发谷歌插件出现错误
错误信息:
Error in event handler for runtime.onInstalled: TypeError: Cannot read property 'sync' of undefined
错误原因
根据官网文档在引入后出错
- manifest.json
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"background" : { "scripts" : [ "background.js"],"persistent" : false },
"manifest_version": 2
}
- background.js
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.sync.set({color: '#3aa757'}, function() {
console.log("The color is green.");
});
});
解决办法
接着看文档后面说明了需要在 manifest.json 文件中加入权限注册
Most APIs, including the storage API, must be registered under the “permissions” field in the manifest for the extension to use them.
更改 manifest.json 文件如下解决问题
{
"name": "Getting Started Example",
"version": "1.0",
"permissions": ["storage"],
"description": "Build an Extension!",
"background" : { "scripts" : [ "background.js"],"persistent" : false },
"manifest_version": 2
}