【问题标题】:How to pass the value to the Text field of Extension Window? (Firefox WebExtension)如何将值传递到扩展窗口的文本字段? (火狐网络扩展)
【发布时间】:2023-03-07 11:39:01
【问题描述】:

我正在尝试为 Firefox 60.0.1 Quantum 编写我的第一个 WebExtension,并寻求您的帮助。

我试图简要描述一下我的 Firefox WebExtension。

  • 步骤 1. 在浏览器面板中,按下扩展按钮,- 打开我的 扩展窗口。

  • 第 2 步。在此扩展窗口中有一个 HTML 页面(文件
    window.html) 带有一个名为“Active Tab URL” (id="url") 的文本字段。

  • 第 3 步。在主浏览器窗口中切换/更新选项卡时,此
    文本字段应包含活动/打开选项卡的 URL。

我的问题:

  1. 如何(从 background.js)向扩展窗口的文本字段 (id="url") 传递任意值?
  2. 如何获取活动选项卡的 URL,以将其传输到我的扩展窗口?

我搜索了网站上的信息:https://developer.mozilla.org/en-US/Add-ons/WebExtensions 但不幸的是,我不明白如何做到这一点。

感谢您的帮助和想法!


ma​​nifest.json

{

  "description": "Adds browser action icon to toolbar to open packaged web page.",
  "manifest_version": 2,
  "name": "Extension Window",
  "version": "1.0",
  "permissions": ["tabs", "contextMenus", "clipboardWrite", "clipboardRead"],
  "icons": {"48": "icons/icon-48.png"},

  "background": {
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icons/icon-32.png"
  }

}

background.js

function openMyWindow() {

    var createWindow = {
    type: "detached_panel",
    url: "window.html",
    titlePreface: "Extension Window",
    width: 350,
    height: 950
    };


    let windowId;

    browser.windows.create(createWindow).then((data) => {
    windowId = data.id;});    

/*
1. How can I pass a any value to the text field (id="url") of my Extension Window?
2. How can I get the URL of the active Tab, to transfer it to my Extension Window?
*/  


}


/*
Add openMyWindow() as a listener to clicks on the browser action.
*/
browser.browserAction.onClicked.addListener(openMyWindow);

window.html

<html>
<head>
<title>Extension Window</title>
<meta charset="utf-8">
</head>
<body>  

<h1>My Extention Window</h1>
<p>Active Tab URL: <input id="url" type="text"></p>
</body>

</html>

【问题讨论】:

    标签: javascript firefox firefox-addon firefox-addon-webextensions


    【解决方案1】:

    有趣的问题,让我们来看看解决方案。

    background.js 中,您将当前(有趣)选项卡的 URL 保存在内存中。由于扩展窗口也是一个选项卡,我们在 setUrlIfDesired 中将其过滤掉。在 onCreated 中,我们过滤 about:blank 和 about:newtab,因为 Firefox 使用这两个来指示选项卡尚未完成加载。

    只要 URL 更改为有趣的内容,我们就会使用 sendMessageToBrowserPopup 通知扩展屏幕它需要更新。

    // Keep URL changes in a variable
    let urlOfCurrentTab = null;
    
    // Keep the id of the created window
    let windowId = -1;
    
    browser.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => {
        if(changeInfo.url) {
            // Here anything is allowed, even about:blank and about:newtab
            setUrlIfDesired("updated", changeInfo.url, tabInfo.active);
        }
    });
    
    browser.tabs.onCreated.addListener((tabInfo) => {
        if(tabInfo.url && tabInfo.active === true){
            if(tabInfo.url !== "about:blank" && tabInfo.url !== "about:newtab"){
                setUrlIfDesired("created", tabInfo.url, tabInfo.active);
            }
        }
    });
    
    browser.tabs.onActivated.addListener((activeInfo) => {
        if(activeInfo.tabId !== -1 && activeInfo.tabId !== null){
            browser.tabs.get(activeInfo.tabId).then((tabInfo) => {
                setUrlIfDesired("activated", tabInfo.url, tabInfo.active);
            });
        }
    });
    
    function setUrlIfDesired(type, url, active){
        console.log(type + ": " + url + " is " + active);
        if(url.indexOf("moz-extension") === -1 && url.indexOf("window.html") === -1){
            urlOfCurrentTab = url;
            console.log("urlOfCurrentTab is now " + urlOfCurrentTab);
            sendMessageToBrowserPopup("getCurrentUrlResult", urlOfCurrentTab);
        }
    }
    
    function openMyWindow(tab) {
    
        browser.windows.create({
            type: "detached_panel",
            url: "window.html",
            titlePreface: "Extension Window",
            width: 350,
            height: 950
        }).then((data) => {
            windowId = data.id;
    
            // The window needs time to create, it gets 1000 milliseconds
            setTimeout(function(){
                setUrlIfDesired("init", tab.url, true); // initialise the current URL
            }, 1000);
        });
    }
    
    // Track whether we need to clear windowId because the window was closed
    browser.windows.onRemoved.addListener((removedWindowId) => {
        if(removedWindowId === windowId){
            windowId = -1;
        }
    });
    
    /* Add openMyWindow() as a listener to clicks on the browser action. */
    browser.browserAction.onClicked.addListener(openMyWindow);
    
    function getCurrentUrl(){
        // You would think this would work, but it doesn't. This is because the extension window is the one that is active!
        /*browser.tabs.query({active: true, currentWindow: true}).then((tabs) => {
            let tab = tabs[0];
            sendMessageToBrowserPopup("getCurrentUrlResult", tab.url);
        });*/
    
        // So we use the urlOfCurrentTab variable that we kept in memory instead.
        sendMessageToBrowserPopup("getCurrentUrlResult", urlOfCurrentTab);
    }
    
    // See also https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/sendMessage
    function sendMessageToBrowserPopup(action, data){
        // Only send messages to the window if it exists
        if(windowId != -1){
            console.log("sending " + data);
            browser.runtime.sendMessage({"action": action, "data": data});
        }
    }
    

    为了让它工作,我们需要编辑window.html

    <html>
    <head>
    <title>Extension Window</title>
    <meta charset="utf-8">
    </head>
    <body>  
    
    <h1>My Extension Window</h1>
    <p>Active Tab URL: <input id="url" type="text"></p>
    <script src="window.js" type="text/javascript"></script>
    </body>
    
    </html>
    

    window.js(一个新文件)中,我们订阅了background.js发出的事件:

    browser.runtime.onMessage.addListener(function(message) {
        switch (message.action) {
            case "getCurrentUrlResult":
                updateTextbox(message.data);
                break;
            default:
                break;
        }
    });
    
    function updateTextbox(urlOfCurrentTab){
        // Update the value in the text box to a new value
        document.getElementById("url").value = urlOfCurrentTab;
    }
    

    你的 manifest.json 很好。了解代码/投入生产时不要忘记删除console.log语句。

    如果您还有其他问题,请随时在 StackOverflow 上提出新问题。

    【讨论】:

    • 还有一个问题。如果从我的网站加载了我的网页“window.html”,为什么它不起作用?网址:“example.com/extension/window.html
    • 可能是因为它无法访问window.js,它应该在浏览器范围内运行,而不是在页面脚本范围内(否则浏览器对象不可用)。页面脚本是由(外部)网站加载/加载到的任何脚本。
    猜你喜欢
    • 2010-11-04
    • 2018-07-22
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多