[英]Chrome-extension / Execute different content scripts depending on selection in popup.html
I need to do an extension with the following behavior. 我需要对以下行为进行扩展。 The popup.html should have two buttons or two radio buttons (button is easier because I don't have to save the selected value like with radio) and depending on the user selection I have to execute one script or another. popup.html应该有两个按钮或两个单选按钮(按钮比较容易,因为我不必像单选一样保存所选的值),并且根据用户选择,我必须执行一个或另一个脚本。 Also after either of the scripts is loaded and the user wants to use the other one, I have to reload the page in order to "unload" the previous one. 同样,在加载了两个脚本中的一个并且用户要使用另一个脚本之后,我必须重新加载页面才能“卸载”前一个脚本。 Could anyone give me an approach to accomplish this? 谁能给我一种方法来实现这一目标?
At the moment I have this: 目前,我有这个:
popup.js popup.js
$(document).ready(function() {
var firstTime = true;
$("input[name='method']").change(function() {
if($(this).val() === "events") {
if(!firstTime) {
chrome.tabs.reload(null, null, function(){
chrome.tabs.executeScript(null, {file: "content_events.js", runAt: "document_end"});
});
} else {
chrome.tabs.executeScript(null, {file: "content_events.js", runAt: "document_end"});
firstTime = false;
}
} else {
if(!firstTime) {
chrome.tabs.reload(null, null, function(){
chrome.tabs.executeScript(null, {file: "content_timer.js", runAt: "document_end"});
});
} else {
chrome.tabs.executeScript(null, {file: "content_timer.js", runAt: "document_end"});
firstTime = false;
}
}
});
});
manifest.json manifest.json
"permissions": [
"tabs",
"activeTab",
"<all_urls>"
],
The first time the script is loaded properly, but when I change it the page reloads but the new script is not loaded (I think it's loaded before the page refresh). 第一次正确加载脚本,但是当我对其进行更改时,页面将重新加载,但是新脚本未加载(我认为它是在刷新页面之前加载的)。 I tried with all the possibilities for the runAt attribute and also without it. 我尝试了runAt属性的所有可能性,也没有尝试。 I tried without injecting the script in the callback function of the tabs.reload too with no luck. 我也尝试没有在tabs.reload的回调函数中注入脚本,但是没有运气。
Thanks for your help! 谢谢你的帮助!
It looks like you want to inject a Javascript file into a page depending on the value of a variable. 您似乎想根据变量的值将Javascript文件注入页面。 You could set a listener with the chrome.tabs.onUpdated method and then call chrome.tabs.executeScript to inject the correct file depending on the value of your variable. 您可以使用chrome.tabs.onUpdated方法设置侦听器,然后根据变量的值调用chrome.tabs.executeScript注入正确的文件。 Be sure to listen for the window load event if you plan on doing any DOM manipulation in your script. 如果计划在脚本中执行任何DOM操作,请确保侦听窗口加载事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.