use*_*282 7 javascript google-chrome-extension
我目前正在开发一个 Google Chrome 扩展程序,它允许 Pinterest 用户轻松地从一个页面固定多个图像(目前不可用的功能)。为了实现这一点,扩展有一个背景页面和两个内容脚本(contentScript1.js 和 contentScript2.js)。为了清楚起见,我将解释我的扩展程序应该做什么,然后详细说明出现了什么问题。我的扩展程序的(简化的)事件顺序是这样的:
好的,除了 contentScript2.js 在任何当前选项卡中执行之外,一切都运行良好。更具体地说,如果我现在打开浏览器,将执行 contentScript2.js 中的 tester 函数。但是,我的 pinterest.com 选项卡仅在适当的时间(单击提交按钮时)创建。根据我的理解,由于 chrome.tabs.create 的默认设置,我不需要在 background.js 和 contentScript2.js 之间使用消息传递。尽管如此,我尝试使用消息传递,但仍然无效?
这是代码:
manifest.json:
{
"manifest_version" : 2,
"name" : "Pin 'em",
"description" : "Pin multiple images to different Pinterest boards in just two clicks",
"version" : "1.1",
"permissions" : [
"tabs",
"<all_urls>"
],
"browser_action" : {
"default_icon" : "images/icon.png"
},
"background" : {
"page" : "background.html",
"persistent" : false
},
"content_scripts" : [
{
"matches" : ["<all_urls>"],
"js" : ["lib/jquery.min.js", "src/contentScript1.js", "src/contentScript2.js"],
"css" : ["stylesheets/style.css"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
和背景页面:
background.js
//when browser icon is clicked, current tab is selected
//sends message to contentScript1.js
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, 'displayImages');
});
});
//when message 'redirectImages' is received
//a new tab is created (url = http://pinterest.com)
//extension executes contentScript2.js in pinterest.com
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'redirectImages') {
sendResponse({received : 'success'});
injectScript();
}
});
function injectScript() {
chrome.tabs.create({url : 'http://pinterest.com'}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: 'src/contentScript2'});
});
};
Run Code Online (Sandbox Code Playgroud)
第一个内容脚本:
contentScript1.js
function sendMess() {
chrome.extension.sendMessage({action : 'redirectImages'}, function(response) {
success = response.received;
console.log(success);
});
};
function appendImages() {
//...does stuff to make a pretty overlay and
//...grabs img tags, and displays for user to select to select
//...appends a submit button with class='submit-images'
};
$(document).on('click', '#submit-images', function(e) {
//..does magic that you need not worry about (i think?)
sendMess();
});
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request === "displayImages") {
appendImages();
}
});
Run Code Online (Sandbox Code Playgroud)
第二个内容脚本
contentScript2.js
function tester() {
console.log('pinterest script injected');
};
var tester = tester();
Run Code Online (Sandbox Code Playgroud)
contentScript2.js在任何当前选项卡中执行
那是因为,在您的清单中,您已将其包含content_scripts在<all_urls>. 似乎您想以编程方式决定何时运行脚本,这正是executeScript用于的目的。
只需contentScript2.js从您的清单中删除,executeScript就会按照您的预期进行注入。
| 归档时间: |
|
| 查看次数: |
13694 次 |
| 最近记录: |