常规网页可以使用 fetch()
或 XMLHttpRequest
API 与远程服务器发送和接收数据,但受到同源政策的限制。内容脚本代表内容脚本注入到的 Web 来源发起请求,因此内容脚本也受同源政策的约束。扩展程序来源并非如此受限。在扩展程序 Service Worker 或前台标签页中执行的脚本可以与其来源之外的远程服务器通信,前提是该扩展程序请求了主机权限。
扩展程序来源
每个正在运行的扩展程序都位于自己的单独安全源中。无需请求其他特权,扩展程序即可调用 fetch()
来获取其安装中的资源。例如,如果某个扩展程序在 config_resources/
文件夹中包含名为 config.json
的 JSON 配置文件,则该扩展程序可以按如下方式检索该文件的内容:
const response = await fetch('/config_resources/config.json');
const jsonData = await response.json();
如果扩展程序尝试从自身以外的安全源(例如 https://www.google.com)请求内容,除非该扩展程序具有主机权限,否则系统会将其视为跨源请求。在内容脚本中,跨源请求始终会被视为跨源请求,即使扩展程序具有主机权限也是如此。
请求跨源权限
如需请求访问扩展程序来源之外的远程服务器,请将主机、匹配模式或二者添加到manifest文件的 host_permissions 部分。
{
"name": "My extension",
...
"host_permissions": [
"https://www.google.com/"
],
...
}
跨源权限值可以是完全限定的主机名,例如:
- "https://www.google.com/"
- "https://www.gmail.com/"
也可以是匹配模式,例如:
- "https://*.google.com/"
- "https://*/"
匹配模式“https://*/”允许通过 HTTPS 访问所有可访问的网域。请注意,此处的匹配模式与内容脚本匹配模式类似,但系统会忽略主机后面的任何路径信息。
另请注意,系统会按主机和架构授予访问权限。如果扩展程序同时需要对给定主机或一组主机拥有安全和不安全的 HTTP 访问权限,则必须单独声明这些权限:
"host_permissions": [
"http://www.google.com/",
"https://www.google.com/"
]
Fetch() 与 XMLHttpRequest()
fetch()
专为服务工件而创建,遵循了远离同步操作的更广泛 Web 趋势。扩展程序在 Service Worker 之外支持 XMLHttpRequest()
API,调用该 API 会触发扩展程序 Service Worker 的提取处理脚本。新工作应尽可能采用 fetch()
。
安全注意事项
避免跨站脚本漏洞
使用通过 fetch()
检索的资源时,您的屏幕外文档、侧边栏或弹出式窗口应注意不要遭到跨网站脚本攻击。具体而言,请避免使用 innerHTML
等危险 API。例如:
const response = await fetch("https://api.example.com/data.json");
const jsonData = await response.json();
// WARNING! Might be injecting a malicious script!
document.getElementById("resp").innerHTML = jsonData;
...
相反,请优先使用不会运行脚本的更安全的 API:
const response = await fetch("https://api.example.com/data.json");
const jsonData = await response.json();
// JSON.parse does not evaluate the attacker's scripts.
let resp = JSON.parse(jsonData);
const response = await fetch("https://api.example.com/data.json");
const jsonData = response.json();
// textContent does not let the attacker inject HTML elements.
document.getElementById("resp").textContent = jsonData;
限制内容脚本对跨源请求的访问权限
代表内容脚本执行跨源请求时,请务必防范可能尝试冒充内容脚本的恶意网页。特别是,请勿允许内容脚本请求任意网址。
请考虑以下示例:一个扩展程序执行跨源请求,以便内容脚本发现商品的价格。一种不太安全的方法是让内容脚本指定后台页面要提取的确切资源。
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == 'fetchUrl') {
// WARNING: SECURITY PROBLEM - a malicious web page may abuse
// the message handler to get access to arbitrary cross-origin
// resources.
fetch(request.url)
.then(response => response.text())
.then(text => sendResponse(text))
.catch(error => ...)
return true; // Will respond asynchronously.
}
}
);
chrome.runtime.sendMessage(
{
contentScriptQuery: 'fetchUrl',
url: `https://another-site.com/price-query?itemId=${encodeURIComponent(request.itemId)}`
},
response => parsePrice(response.text())
);
在上述方法中,内容脚本可以请求扩展程序提取扩展程序有权访问的任何网址。恶意网页可能会伪造此类消息,并诱骗扩展程序授予对跨源资源的访问权限。
而是设计消息处理脚本,以限制可提取的资源。在下面的示例中,内容脚本仅提供 itemId
,而非完整网址。
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == 'queryPrice') {
const url = `https://another-site.com/price-query?itemId=${encodeURIComponent(request.itemId)}`
fetch(url)
.then(response => response.text())
.then(text => parsePrice(text))
.then(price => sendResponse(price))
.catch(error => ...)
return true; // Will respond asynchronously.
}
}
);
chrome.runtime.sendMessage(
{contentScriptQuery: 'queryPrice', itemId: 12345},
price => ...
);
优先使用 HTTPS(而非 HTTP)
此外,请特别注意通过 HTTP 检索的资源。如果您的扩展程序在恶意网络上使用,网络攻击者(也称为"man-in-the-middle")可能会修改响应,并可能攻击您的扩展程序。相反,请尽可能使用 HTTPS。
调整内容安全政策
如果您通过向清单添加 content_security_policy
属性来修改扩展程序的默认内容安全政策,则需要确保您要连接的所有主机都已获准。虽然默认政策不会限制与主机的连接,但在明确添加 connect-src
或 default-src
指令时,请务必小心。