按下按钮时动态注入脚本
Injection of scripts dynamically at button press
单击时我的网页上的按钮执行以下操作,即将脚本注入页面
function InjectToolbar() {
var script = document.createElement('script');
scriptFarfalla.src = 'some_Path'
document.getElementsByTagName('head')[0].appendChild(script);
}
......
它成功地执行了所需的操作。但是当我重新加载页面时,脚本丢失了
有什么方法/技术可以缓冲按钮的点击像一个切换按钮
切换.....>注入脚本
切换.....>脚本已分离
JavaScript中发生的所有事情都会在你离开页面(并返回页面)时重置。因此,您需要一种方法来存储某些内容是否已加载。这取决于您希望将其"保存"/"记住"多长时间。您可以通过几个选项来保存此信息 - Cookie、HTML5 localStorage、HTML5 sessionStorage以及您可用的任何服务器会话使用情况(如果适用)。因此,如果你想实现这样的东西,你现在需要你的页面的代码加载来检查特定的存储,看看你是否已经设置了它。如果是这样,请注入脚本。我的意思是:
window.onload = function () {
if (checkIfInjected()) {
scriptInjection(true);
}
}
function toggleInjection() {
if (checkIfInjected()) {
scriptInjection(false);
} else {
scriptInjection(true);
}
}
function scriptInjection(inject) {
if (inject == true) {
var script = document.createElement('script');
script.src = 'some_Path';
script.id = 'injected_script_id';
document.getElementsByTagName('head')[0].appendChild(script);
// Set the storage to say that script is injected
} else {
var the_script = document.getElementById("injected_script_id");
the_script.parentNode.removeChild(the_script);
the_script = null;
// Set the storage to say that script has been removed (or remove from storage altogether)
}
}
function checkIfInjected() {
// The following syntax is wrong for anything - you need to use the correct getter for the storage type you use
return storage.contains("script_injected");
}
<input type="button" id="button1" onclick="toggleInjection();" />
现在由您决定所需的存储类型,因为它们都执行不同的操作,包括存储方式、存储内容以及存储时间。
您可以使用 cookie 来存储已注入的脚本,然后在页面加载时重新注入它们。Cookie 和较新的本地存储是在客户端上存储状态的常用方法。
相关文章:
- Safari扩展中的注入脚本;不要在Youtube上开火
- 通过innerHTML注入脚本:函数与全局
- 如何在访问其他url时在nodewebkit中注入脚本
- 按下按钮时动态注入脚本
- 是的.js在已加载的脚本上方注入脚本
- Chrome 扩展程序:在注入脚本之前,将数据从弹出窗口传递到另一个脚本文件
- 注入脚本以播放音频文件,如果 InnerText 与字符串不匹配
- 如何同步注入脚本
- 将值传递到“;注入脚本”;而不是依赖全局
- 正在使用ngBindHtml注入脚本标记
- 获取调用注入脚本的选项卡的url
- 如何在谷歌页面上搜索后注入脚本
- Chrome扩展:错误时发送消息从注入脚本回后台脚本
- 在注入脚本中使用扩展的localStorage包装器函数
- 从注入脚本到带有响应的内容脚本的通信
- 如何在protractor的浏览器实例中手动注入脚本标记
- tabs.executeScript()没有在扩展的内容页中注入脚本
- 错误注入脚本在其他选项卡在我的chrome扩展
- Angular 2 JSONP注入脚本没有调用回调错误
- Chrome扩展在页面加载前注入脚本