【发布时间】:2020-03-04 23:17:24
【问题描述】:
我正在尝试制作一个 chrome 扩展,它从后端接收 javascript 代码并将其保存在 localStorage(作为 base64)中,以便稍后在加载正确的页面时将其作为内容脚本注入,它确实可以在大多数情况下工作除了有几个问题之外的时间......第一个问题(不是那么重要)是我无法访问 Chrome API(如 chrome.storage 或 chrome.runtime.sendMessage),第二个问题是它没有注入正确的代码到子 iframe... 因为 location.href 返回顶部网页的 URL,我找不到在 iframe 本身内访问 iframe 当前 URL 的方法。
这是我目前的代码:
manifest.json
//....
"content_scripts": [{
"run_at": "document_end",
"all_frames": true,
"matches": [
"<all_urls>"
],
"js": [
"src/inject/InjectManager.js"
]
}],
//...
InjectManager.js:
// Some functions were not included for brevity
chrome.runtime.sendMessage({ action: "get_supported_urls" }, function(supported_urls) {
let current_url = window.location.href;
// Check if we support current_url
let js_code_to_inject = isWebsiteSupported(supported_urls, current_url); // this function returns string that is javascript code.
if(js_code_to_inject){
// Append the code to the body
let script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = js_code_to_inject;
document.body.appendChild(script);
}
});
如您所见,我正在尝试重新创建 chrome 在 manifest.json 的“content_script”部分中已经完成的功能,因为我的 javascript 代码是动态的。
注意:我知道这在 chrome 商店中是不允许的,因此此扩展程序不得与任何人共享。
感谢阅读。 任何帮助将不胜感激。
【问题讨论】:
标签: javascript google-chrome iframe google-chrome-extension content-script