是否可以注入一个 javascript 代码来覆盖 DOM 中现有的代码?(例如默认警报功能) [英] Is it possible to inject a javascript code that OVERRIDES the one existing in a DOM? (e.g default alert function)

查看:16
本文介绍了是否可以注入一个 javascript 代码来覆盖 DOM 中现有的代码?(例如默认警报功能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我想要的是覆盖选项卡中已经存在的方法,我将使用的是默认警报功能.在 JS 函数中覆盖它会很容易.只需添加

Ok, so what I want is to override a method that already exists inside a tab, what I'm going to use is the default alert function. Override it inside the JS function would be very easy. just add

window.alert = function(){ 
   //Do Something
}

但问题是当我尝试使用 chrome.tabs.executeScript("window.alert = function() { };"); 它不起作用.我尝试通过在要覆盖该功能的选项卡中使用 Chrome 中的控制台手动执行此操作,我在日志中键入该覆盖功能并按 Enter,完成后,警报功能被覆盖,但我做不到这是通过 Chrome 扩展程序实现的.

but the problem is that when I try to use chrome.tabs.executeScript("window.alert = function() { };"); it doesn't work. I tried to do this manually by using the Console from Chrome in the tab that I wanted to override the function, I typed that override function in the log and pressed enter, and done, the alert function was overridden, but I can't do this via Chrome Extension.

当您添加 executeScript 时,它似乎创建了一个与 tab DOM 内部的 Javascript 不同的 Javascript,因为我可以使用 tab DOM 中已经存在的函数的名称创建函数.

When you add executeScript, it seems like it creates a Javascript apart from the one inside the tab DOM, because I can create functions with the name of a function that already exists inside the tab DOM.

有没有办法让 executeScript 在 tab DOM 内部编写脚本,这样它实际上可以覆盖由页面生成的 .js 文件编写的任何函数?

Is there a way to make executeScript to write the script inside of the tab DOM, so it can actually override any function that was written by the .js file the page generated?

谢谢!

推荐答案

函数不作为 DOM 的一部分存在;相反,它们存在于包含 DOM 的执行环境中.内容脚本(包括使用 executeScript) 和实际网页共享相同的 DOM,但具有 单独的执行环境.因此,调用 window.alert = function() {} 只会在内容脚本的执行环境中重写 window.alert,而不是在实际页面的执行环境中.

Functions don't exist as part of the DOM; instead, they exist within an execution environment that includes the DOM. Content scripts (including scripts run with executeScript) and actual web pages share the same DOM, but have separate execution environments. So calling window.alert = function() {} only rewrites window.alert within your content script's execution environment, not in the actual page's one.

到达实际页面执行环境的典型方式是在DOM中注入一个

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆