[英]Chrome Extension: create new tab(chrome.tabs.create) and executeScript in new tab…not working :(
我目前正在開發Google Chrome擴展程序,允許Pinterest用戶輕松地從頁面固定多個圖像(目前無法使用的功能)。 為實現此目的,擴展程序具有后台頁面和兩個內容腳本(contentScript1.js和contentScript2.js)。 為清楚起見,我將解釋我的擴展應該做什么,然后詳細說明出現了什么問題。 我的擴展(簡化)事件順序如下:
好的,除了在任何當前選項卡中執行contentScript2.js之外,一切都工作正常。 更具體地說,如果我現在打開瀏覽器,將執行contentScript2.js中的測試器功能。 但是,我的pinterest.com選項卡僅在適當的時間創建(單擊提交按鈕時)。 根據我的理解,我不需要在background.js和contentScript2.js之間使用消息傳遞,因為chrome.tabs.create的默認設置。 盡管如此,我嘗試使用消息傳遞,它仍然無法正常工作☹
這是代碼:
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"]
}
]
}
和背景頁面:
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'});
});
};
第一個內容腳本:
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();
}
});
第二個內容腳本
contentScript2.js
function tester() {
console.log('pinterest script injected');
};
var tester = tester();
contentScript2.js
在任何當前選項卡中執行
這是因為,在您的清單中,您已將其包含在加載<all_urls>
content_scripts
中。 您似乎希望以編程方式決定何時運行腳本,這正是executeScript
的用途。
只需從清單中刪除contentScript2.js
, executeScript
就會按預期進行注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.