如何在Chrome扩展程序中重定向当前标签页的网址? [英] How to redirect current tab's url in Chrome extension?

查看:68
本文介绍了如何在Chrome扩展程序中重定向当前标签页的网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Chrome扩展程序,用于在不同的搜索引擎之间切换. manifest.json 如下:

I'm writing a Chrome extension, used to switch between different search engines. The manifest.json looks like:

{
    "browser_action": {
        "default_popup": "popup.html"
        },
    "permissions": [
        "tabs",
        "activeTab"
        ],
    "content_security_policy": "script-src 'self'; object-src 'self'",
    "content_scripts": [{
        "matches": ["*://*.baidu.com/*"],
        "js": ["content.js"]
        }]
}

  • content.js 用于获取搜索中的用户关键字.
  • popup.html 包含受支持的搜索引擎的列表.
    • content.js is used to get user's keywords in searching.
    • popup.html contains a list of supported search engines.
    • 当用户在弹出窗口中单击搜索引擎的图标时,我需要使用选定的搜索引擎用户将当前选项卡重定向到新的url.

      When user clicks on search engine's icon in popup window, I need to redirect current tab to a new url using the search engine user selected.

      现在我可以获取关键字了.问题是:如何将当前标签页重定向到新网址?

      Now I can get keyword. Problem is: How to redirect current tab to new url?

      推荐答案

      有2种可能的方法:

      A.让弹出窗口处理重定向.
      B.让内容脚本处理重定向.

      A. Let the popup handle redirection.
      B. Let the content script handle redirection.

      在两种情况下,您都需要解决两个问题:

      In both cases, you need to solve 2 problems:

      1. 在两者之间交流信息.在方法A中,您需要从内容脚本中获取关键字.在方法B中,您需要告诉内容脚本要切换到哪个引擎.

      1. Communicate information between the two. In approach A, you need to get the keywords from the content script. In approach B, you need to tell the content script which engine to switch to.

      两者均使用消息传递解决.我建议使用 chrome.tabs.sendMessage 从弹出窗口向内容脚本发送消息(并在方法A中进行响应),因为从另一个方向看,内容脚本不知道何时发送消息(弹出窗口可能被关闭).

      Both are solved using Messaging. I recommend messaging from the popup to the content script using chrome.tabs.sendMessage (and responding in approach A), because in the other direction content script doesn't know when to send the message (popup may be closed).

      实际上触发更改.在方法A中, chrome.tabs.update 确实可以诀窍.在方法B中,内容脚本可以更改 window.location 进行导航.

      Actually trigger the change. In approach A, chrome.tabs.update does the trick. In approach B, content script can change window.location to navigate away.

      这篇关于如何在Chrome扩展程序中重定向当前标签页的网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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