[英]How to redirect current tab's url in Chrome extension?
I'm writing a Chrome extension, used to switch between different search engines.我正在编写一个 Chrome 扩展程序,用于在不同的搜索引擎之间切换。 The
manifest.json
looks like: manifest.json
看起来像:
{
"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
is used to get user's keywords in searching. content.js
用于获取用户在搜索中的关键字。popup.html
contains a list of supported search engines. popup.html
包含支持的搜索引擎列表。 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.当用户在弹出窗口中单击搜索引擎的图标时,我需要使用所选的搜索引擎用户将当前选项卡重定向到新的 url。
Now I can get keyword.现在我可以得到关键字。 Problem is: How to redirect current tab to new url?
问题是:如何将当前标签重定向到新的 url?
See chrome.tabs.update
, you could update the url of current tab via the following code参见
chrome.tabs.update
,您可以通过以下代码更新当前选项卡的 url
chrome.tabs.update({url: "http://www.baidu.com"});
Considering you get the keyword from content script, and want to redirect the url after user clicks some button in popup page, you may need Message Passing or chrome.storage to share the keywords between content script and popup page.考虑到您从内容脚本中获取关键字,并希望在用户单击弹出页面中的某个按钮后重定向 url,您可能需要消息传递或chrome.storage在内容脚本和弹出页面之间共享关键字。
There are 2 possible approaches:有两种可能的方法:
A. Let the popup handle redirection. A. 让弹出窗口处理重定向。
B. Let the content script handle redirection. B. 让内容脚本处理重定向。
In both cases, you need to solve 2 problems:在这两种情况下,您都需要解决两个问题:
Communicate information between the two.沟通两人之间的信息。 In approach A, you need to get the keywords from the content script.
在方法 A 中,您需要从内容脚本中获取关键字。 In approach B, you need to tell the content script which engine to switch to.
在方法 B 中,您需要告诉内容脚本要切换到哪个引擎。
Both are solved using Messaging .两者都使用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).我建议使用
chrome.tabs.sendMessage
(并在方法 A 中响应)从弹出窗口向内容脚本发送消息,因为在另一个方向内容脚本不知道何时发送消息(弹出窗口可能已关闭)。
Actually trigger the change.实际触发变化。 In approach A,
chrome.tabs.update
does the trick.在方法 A 中,
chrome.tabs.update
可以解决问题。 In approach B, content script can change window.location
to navigate away.在方法 B 中,内容脚本可以更改
window.location
以导航离开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.