谷歌浏览器扩展+ chrome.windows.create + window.getSelection()。toString()

时间:2017-01-17 20:55:48

标签: javascript google-chrome google-chrome-extension

我正在开发一个chrome扩展程序,它将选定/突出显示的文本复制到textarea中。这就是我到目前为止所使用的:

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();",
}, function(selection) {
    document.getElementById("output").value = selection[0];
});

但现在我已经从popup.html切换到我创建的窗口

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.windows.create({
        url: chrome.runtime.getURL("window.html"),
        type: "panel", height: 590, width:850, focused: false
        }, function(win) {
    });
});

我无法再将所选文本输入此窗口。我还复制了activetab的当前URL,如下所示:

chrome.tabs.getSelected(windowId, function(tab) {
    document.getElementById('url').innerHTML = tab.url;
    var windowId = tab.id
});

我可以使用以下方法为新窗口工作:

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    document.getElementById('url').innerHTML = tabs[0].url;
});

所以我的问题是:如何将所选/突出显示的文本放入我新创建的窗口内的textarea?是否有类似于

的内容
chrome.tabs.query() 

仅针对突出显示的文字?

1 个答案:

答案 0 :(得分:0)

使用executeScript的tabId参数注入单击的选项卡,然后使用以下任何一个传递文本:

  • whose registered scope is most specific
  • messaging
  • 网址中的
  • chrome.storage.local'window.html?url=' + encodeURIComponent(text)
    然后在window.js中使用decodeURIComponent。
  • localStorage,所有内部扩展页面之间共享的经典同步存储,如果您需要在第一页上显示结果而没有延迟/闪烁,并且不想在URL中传递文本。

这是localStorage的一个例子。

  • background.js:

    chrome.browserAction.onClicked.addListener(function(tab) {
        getSelectedText(tab.id, function(text) {
            localStorage.selectedText = text;
            chrome.windows.create({
                url: "/window.html",
                type: "panel", height: 590, width:850, focused: false
            });
        });
    });
    
    function getSelectedText(tabId, cb) {
        chrome.tabs.executeScript(tabId, {
            code: "window.getSelection().toString();",
        }, function(selection) {
            cb(selection[0]);
        });
    }
    
  • window.html:

            .................
            <script src="window.js"></script>
        </body>
    </html>
    
  • window.js:

    document.getElementById('url').textContent = localStorage.selectedText || '';
    delete localStorage.selectedText;