我有一个 Chrome 扩展,可以通过浏览器操作单击来切换侧边栏。侧边栏包含一个带有本地(chrome 扩展)源的 iframe。我认为 iframe 中的页面将被视为本地 chrome 扩展文件,可以开放访问 chrome API 等。但是,我不断收到以下错误web安慰:
未捕获的类型错误:无法读取未定义的属性“onClicked”
类型错误:无法读取未定义的属性“查询”
如何获取它以便注入上下文脚本的 iframe 可以访问本地 chrome 环境?
代码如下:
侧边栏.js:
var myApp = angular.module('PlaceMates', []);
myApp.service('pageInfoService', function() {
this.getInfo = function(callback) {
var model = {};
chrome.tabs.query({
'active': true, // Select active tabs
lastFocusedWindow: true // In the current window
},
function (tabs) {
if (tabs.length > 0)
{
model.title = tabs[0].title;
model.url = tabs[0].url;
chrome.tabs.sendMessage(tabs[0].id, { 'action': 'PageInfo' }, function (response) {
model.pageInfos = response;
console.log("popup js: " + model.pageInfos);
callback(model);
});
}
});
};
});
myApp.controller("PageController", function ($scope, pageInfoService) {
$scope.message = "This extension identifies the photos on this page!";
pageInfoService.getInfo(function (info) {
$scope.title = info.title;
$scope.url = info.url;
$scope.pageInfos = info.pageInfos;
$scope.place_name = info.place_name;
$scope.$apply();
});
});
背景.js
console.log( 'Background.html starting!' );
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
console.log('Toggling sidebar on ' + tab.url);
// send message to current tab when clicked
var tabId = tab.id;
console.log("tab.id: " + tabId);
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
chrome.tabs.sendMessage(
//Selected tab id
tabId,
//Params inside a object data
{callFunction: "toggleSidebar"},
//Optional callback function
function(response) {
console.log(response);
}
);
});
console.log('Done toggling sidebar!');
});
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.cmd == "read_file") {
$.ajax({
url: chrome.extension.getURL("sidebar.html"),
dataType: "html",
success: sendResponse
});
}
})
chrome.runtime.onMessage.addListener(
function(msg, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (msg.command == "read_info"){
console.log(JSON.parse(JSON.stringify(msg.myInfo)));
sendResponse({command: "done"});
}
}
);
console.log( 'Background.html done.' );