在browser_action Chrome扩展中设置当前选项卡的window.location.href [英] Setting window.location.href of the current tab in a browser_action Chrome Extension

查看:387
本文介绍了在browser_action Chrome扩展中设置当前选项卡的window.location.href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将当前标签导航到browser_action Chrome扩展程序中的网址,以响应用户输入的关键字。最好的方法是什么?



首先我尝试了一个带有javascript的简单表单,但是我意识到javascript并未在当前选项卡上设置window.location.href因为我没有使用executeScript。

到目前为止,我发现的最好的方法是使用executeScript:

  chrome.tabs.executeScript(null,{code:window.location.href ='+ url +';}); 

这还包括为清单添加权限:

 permissions:[
tabs,
http:// * /,
https:// * /
],

问题是:


  1. 这种方法在newtab页面上不起作用。 (添加chrome:// * /会中断扩展并阻止它被安装)

  2. 它需要为每个协议类型明确设置权限,否则该扩展程序将无法在某些类型的页面上工作。



  3. Chrome选项卡将打开的选项卡导航到browser_action弹出窗口中的特定页面?

    解决方案

    不需要内容脚本或主机权限。只需使用 chrome.tabs.update (不需要标签权限):

    chrome.tabs.update(tab.id,{$ b $ url:url
    });
    } );


    I'm trying to navigate the current tab to a URL in a browser_action Chrome extension, in response to a keyword that a user has entered. What's the best way to do this?

    First I tried a simple form with javascript, but I realized that the javascript was not setting window.location.href on the current tab because I wasn't using executeScript.

    So far the best method I've found is to use executeScript:

    chrome.tabs.executeScript(null, {code:"window.location.href = '" + url + "';"});
    

    This also involves adding permissions to the manifest:

    "permissions": [
      "tabs",
      "http://*/",
      "https://*/"
    ],
    

    The problem is that:

    1. This approach doesn't work on newtab pages. (adding "chrome://*/" breaks the extension and prevents it from being installed)

    2. It requires that permission be explicitly set for every single protocol type, else the extension won't work on some types of pages.

    Is there a more robust way of making a Chrome tab navigate the open tab to a particular page from a browser_action popup?

    解决方案

    There's no need for content scripts or host permissions. Just use chrome.tabs.update (the tabs permission is not needed):

    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.update(tab.id, {
            url: url
        });
    });
    

    这篇关于在browser_action Chrome扩展中设置当前选项卡的window.location.href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆