简体   繁体   English

使用Chrome扩展程序修改或阻止内容JS功能

[英]Modify or block contents JS function with Chrome extension

I need to block writing to LocalStorage. 我需要阻止写入LocalStorage。 So when the function localstorage.setItem() is called, I need to change it's behaviour or block. 因此,当调用函数localstorage.setItem() ,我需要更改其行为或阻止。 I have my content.js in "content_scripts" of manifest 我的清单的"content_scripts"中有我的content.js

Here are possible ways (I can't find anything on all of them): 以下是一些可能的方法(我在所有方法上都找不到):

1) Event handler of storage change 1)存储变更的事件处理程序

I've tried 我试过了

window.addEventListener('storage', function (event) {
    console.log("storage event occured here");
});

But I need detection of function call in the same tab (through extension). 但是我需要在同一选项卡(通过扩展名)中检测函数调用。

2) Override system function localstorage.setItem() 2)覆盖系统函数localstorage.setItem()

It works if I will write in console 如果我将在控制台中编写它会起作用

localStorage.setItem = function(){
    console.log('modified');
  }

But not if in content.js 但是如果不是在content.js中

Also tried to add to manifest "run_at" : "document_start" for content_scripts 还尝试为content_scripts添加清单"run_at" : "document_start"

3) Event handler of setItem function call 3)setItem函数调用的事件处理程序

Is it possible to set trigger/handler for custom function call? 是否可以为自定义函数调用设置触发器/处理程序? I know handlers like click, mouseover.. but on function calls - not. 我知道处理程序如单击,鼠标悬停..但在函数调用上-不。

The answer is to inject script file through contents script. 答案是通过内容脚本注入脚本文件。 Thanks to wOxxOm 感谢wOxxOm

content.js content.js

var inj = document.createElement('script');
inj.src = chrome.runtime.getURL('blockaccess.js');
inj.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(inj);

blockaccess.js blockaccess.js

Storage.setItem = localStorage.setItem = sessionStorage.setItem = function(){
  console.log('Blocked Storage setItem()');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM