在 Chrome 扩展中绕过 X-Frame-Options DENY?
IT技术
javascript
iframe
google-chrome-extension
x-frame-options
2021-01-31 17:28:25
2个回答
Chrome 提供webRequest
API 来拦截和修改 HTTP 请求。您可以删除X-Frame-Options
标题以允许在 iframe 中内联页面。
chrome.webRequest.onHeadersReceived.addListener(
function(info) {
var headers = info.responseHeaders;
for (var i=headers.length-1; i>=0; --i) {
var header = headers[i].name.toLowerCase();
if (header == 'x-frame-options' || header == 'frame-options') {
headers.splice(i, 1); // Remove header
}
}
return {responseHeaders: headers};
}, {
urls: [
'*://*/*', // Pattern to match all http(s) pages
// '*://*.example.org/*', // Pattern to match one http(s) site
],
types: [ 'sub_frame' ]
}, [
'blocking',
'responseHeaders',
// Modern Chrome needs 'extraHeaders' to see and change this header,
// so the following code evaluates to 'extraHeaders' only in modern Chrome.
chrome.webRequest.OnHeadersReceivedOptions.EXTRA_HEADERS,
].filter(Boolean)
);
在清单中,您需要指定webRequest
和webRequestBlocking
权限,以及您打算拦截的URL 模式,即"*://*/*"
或"*://www.example.org/*"
上面的示例。
使用 declarativeNetRequest 的 ManifestV3 示例
让我们使用新的declarativeNetRequest API 仅在 iframe 嵌入到我们的扩展程序的页面中时剥离标头。
清单.json:
"permissions": ["declarativeNetRequest"],
"host_permissions": ["*://*.example.com/"],
"background": {"service_worker": "bg.js"},
bg.js:
const iframeHosts = [
'example.com',
];
chrome.runtime.onInstalled.addListener(() => {
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: iframeHosts.map((h, i) => i + 1),
addRules: iframeHosts.map((h, i) => ({
id: i + 1,
condition: {
domains: [chrome.runtime.id],
urlFilter: `||${h}/`,
resourceTypes: ['sub_frame'],
},
action: {
type: 'modifyHeaders',
responseHeaders: [
{header: 'X-Frame-Options', operation: 'remove'},
{header: 'Frame-Options', operation: 'remove'},
],
},
})),
});
});
其它你可能感兴趣的问题