2014-11-23 209 views
1

我正在開發一個簡單的擴展,但我無法弄清楚如何繼續前進。我想這是一個'簡單'的問題。Chrome擴展程序,在標籤頁之間發送數據

場景:

  • 用戶選擇的文本
  • 打開上下文菜單,然後按下擴展
  • 一個新標籤頁打開
  • 填寫一個文本瓦特/選擇/高亮文本

我做了前三項,第四項我嘗試了chrome.tabs.query/executeScript/messaging,ajax post ... 沒有成功。

function sendReport() { 
    return function(info, tab) { 
     var selectedText = info.selectionText; 
     var cr_url = 'http://localhost/cr/index.php'; 
     var tab = chrome.tabs.create({ url: cr_url }, function(tab){ 

     }); 
    } 
} 

var OgameToConverter = chrome.contextMenus.create({ 
    "title": "Enviar Relatório", 
    "contexts": ["selection"], 
    "onclick": sendReport() 
}); 

回答

1

您可以通過使用chrome.runtime.sendMessagechrome.tabs.sendMessage發送選項卡之間的消息。要接收消息,請使用chrome.runtime.onMessage.addListener方法在接收選項卡上添加消息的偵聽器。

例子:

chrome.tabs.create({ url: cr_url }, function(tab){ 
    chrome.tabs.sendMessage(tab.id, {greeting: "hello"}), function(){}); 
}); 

在標籤:

chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) { 
    // do what you want to the message 
}); 

或者,您可以用window.open創建窗口,與window.postMessage發送消息,並通過捕捉Message事件東西收到消息像window.addEventListener("message", ...);

+0

我不知道。也許我是用錯誤的方式來構建它的...... 我有第1頁 - http://example.com,當我突出顯示一個文本並在上下文菜單上點擊擴展項時,它會打開第2頁 - http ://stuff.org(不同的網站),並用選定的文本填充一個textarea 所以當你說'在標籤中',你的意思是? – 2014-11-23 04:17:16

+0

我的意思是這段代碼將運行在你想要通過文本的標籤上。 – 0xcaff 2014-11-23 05:18:52

+0

@ 0xcaff只是一點點更新。需要刪除'{greeting:「hello」}'後的額外括號。我無法編輯您的答案,因爲StackOverflow預計至少需要6個字符的編輯變化! – 2017-11-10 06:41:37

相關問題