[英]How to dynamically append the content script in browser extension.?
I am trying to append the script on content script from the API response.我正在尝试 append 来自 API 响应的内容脚本上的脚本。
Following is the content.js以下是 content.js
locationHref = window.location.href;
chrome.runtime.sendMessage({
action: locationHref,
value: false
}, function (data) {
localStorage();
console.log('contetn js ', data);
});
function localStorage() {
chrome.storage.local.get('script', (items) => {
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = items.script;
document.body.appendChild(s);
if (items.responseData) {
setTimeout((r) => {
loadPopUp(items.responseData); // this method is not triggering
}, 5000);
}
});
}
And following is the background.js file以下是 background.js 文件
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
fetchData(msg.action, sendResponse);
return true;
});
function fetchData(url, sendResponse) {
fetch("myscript.js", {
method: 'GET',
}).then(res => res.json())
.then(response => {
chrome.storage.local.set({
"script": response
}, function () {});
sendResponse(response);
}).catch(error => {
console.log(error)
});
}
And myscript.js has the following code. myscript.js 有以下代码。
function loadPopUp(data) {
document.body.insertAdjacentHTML('beforeend', `<h4 style="color:white; font-size: 25px; text-align: center; margin-top: 15px;">
${data.name} has <span style="font-weight:bold">${data.count}</span> gene count</h4>`)
}
API response has the loadPopUp() method, after creating the script tag I am trying to call the loadPopup method but it is giving undefined
error. API 响应具有 loadPopUp() 方法,在创建脚本标记后,我试图调用 loadPopup 方法,但它给出了undefined
的错误。
How can I solve this problem.?我怎么解决这个问题。?
I have had success in embedded environments (ie, where I do not have access to the main page code) loading the scripts directly into the head.我在将脚本直接加载到头部的嵌入式环境(即,我无法访问主页代码)中取得了成功。
Here is what I do.这就是我所做的。
const exampleScript = {
name: "p5.js",
src: "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js",
id: "p5-script"
};
const loadScript = (scriptToLoad, callback) => {
let script = document.createElement("script");
script.src = scriptToLoad.src;
script.id = scriptToLoad.id;
script.onload = () => {
callback();
}
script.onerror = (e) => console.error("error loading" + scriptToLoad.name + "script", e);
document.head.append(script);
}
loadScript(exampleScript, () => {
//...whatever you do after loading the script
});
The issue you are likely having is that you load it into the body instead of into the head.您可能遇到的问题是将其加载到身体而不是头部。
Here is an article that explains it.这是一篇解释它的文章。 https://aaronsmith.online/easily-load-an-external-script-using-javascript/ https://aaronsmith.online/easy-load-an-external-script-using-javascript/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.