JavaScript书签工具获取URL异常:返回about:srcdoc而非实际页面地址
解决书签工具获取真实页面URL的问题
问题出在srcdoc嵌入的iframe是独立的文档环境,它的window.location.href指向的是自身的about:srcdoc,而非打开它的原页面。你只需要把获取URL的代码改成访问父页面的window对象即可:
核心修改点
把表单提交事件里的window.location.href替换成window.parent.location.href。window.parent指向的是打开这个弹窗/iframe的原页面的窗口对象,它的location.href就是你需要的真实页面URL。
示例代码调整
比如你原来的提交事件代码可能是这样:
document.querySelector('form').addEventListener('submit', function(e) { e.preventDefault(); // 错误写法:获取的是iframe自身的地址 // const pageUrl = window.location.href; // 正确写法:获取原页面地址 const pageUrl = window.parent.location.href; // 获取用户输入 const userInput = document.querySelector('input[name="content"]').value; // 拼接工单URL const ticketUrl = `https://你的内部工单系统地址?page=${encodeURIComponent(pageUrl)}&content=${encodeURIComponent(userInput)}`; // 打开工单页面 window.open(ticketUrl, '_blank'); // 关闭弹窗 window.close(); });
书签let生成注意事项
在用工具生成书签let时,要确保代码里的特殊字符(比如引号、换行)被正确转义,避免运行报错。比如把上面的代码整合到书签let的弹窗生成逻辑里,最终的书签代码大概是这样(简化版):
javascript:(function(){const pop=window.open('','ticketPopup','width=450,height=350');pop.document.write('<html><body><form><p>问题描述:<input type="text" name="desc" required></p><button type="submit">生成工单</button></form><script>document.querySelector("form").addEventListener("submit",function(e){e.preventDefault();const realUrl=window.parent.location.href;const desc=e.target.desc.value;const url="https://你的工单系统.com/new?url="+encodeURIComponent(realUrl)+"&desc="+encodeURIComponent(desc);window.open(url,"_blank");window.close();});<\/script></body></html>');pop.document.close();})();
如果之前报错,大概率是没正确引用window.parent,或者代码转义时出了问题,检查下引号和闭合标签是否正确即可。
内容的提问来源于stack exchange,提问作者Vanassins
相关产品推荐
相关产品推荐

