Chrome浏览器中如何让JavaScript Snippets在页面刷新后正常执行
问题原因
点击链接触发页面跳转后,原页面的JavaScript执行上下文会被浏览器销毁,未执行的后续代码直接失效,而单独在新页面控制台执行时是运行在新页面的上下文环境中,因此可以正常生效。另外你原代码里有个笔误:getElementsbyClassName的b需要大写,正确写法是getElementsByClassName。
解决方案
方案1:使用Tampermonkey(油猴)脚本(最稳定的自动化方案)
油猴脚本可以匹配指定页面,页面加载完成后自动执行对应逻辑,无需手动触发:
// ==UserScript== // @name 工单状态自动修改工具 // @match *://你的列表页域名/列表页路径* // @match *://你的详情页域名/详情页路径* // @grant none // ==/UserScript== (() => { // 列表页逻辑:点击对应链接跳转到详情页 const listTable = document.getElementById("incident_table"); if (listTable) { listTable.rows[2].cells[2].getElementsByClassName("linked")[0].click(); return; } // 详情页逻辑:修改下拉框并提交 const stateSelect = document.getElementById("incident.state"); if (stateSelect) { stateSelect.selectedIndex = 1; document.getElementById("sysverb_update").click(); } })();
使用时把@match后面的地址替换为你实际的列表页、详情页地址规则,保存脚本后打开列表页就会自动走完完整流程。
方案2:结合localStorage的Snippet方案
如果不想安装浏览器扩展,可以用Snippet配合本地存储实现状态流转,只需要把以下代码保存为Chrome Snippet:
// 替换为你实际的列表页完整地址 const LIST_PAGE_URL = "https://你的列表页地址"; if (location.href === LIST_PAGE_URL) { // 列表页执行点击跳转逻辑 const tbl = document.getElementById("incident_table"); tbl.rows[2].cells[2].getElementsByClassName("linked")[0].click(); localStorage.setItem("auto_process_incident", "1"); } else if (localStorage.getItem("auto_process_incident") === "1") { // 详情页执行修改提交逻辑,执行完删除标记 localStorage.removeItem("auto_process_incident"); document.getElementById("incident.state").selectedIndex = 1; document.getElementById("sysverb_update").click(); }
使用时在列表页运行一次Snippet,跳转到详情页后再次运行Snippet即可完成操作。

内容的提问来源于stack exchange,提问作者Manivannan Nagarajan
相关产品推荐
相关产品推荐

