I want to use extensions to read json files in extensions

Asked 1 years ago, Updated 1 years ago, 394 views

The whole thing you want to do

Extensions detect notifications implemented on the website and block notifications when url in the block list is transition destination url
I would like to read the json file (block list) in the extension function by the extension function and compare the url registered in the json file with the transition destination url obtained.
The method can be fetch or xmlhttprequest.

What I want to do this time

Want to read json files in extensions within extensions
content.js if(url==="blacklist url"){} in content.js I want to get the contents of the json file above this process

What I don't know

·Can't the content.js of manifest content_scripts perform asynchronous processing?
·Blocked.json in content.js relative path but not read

Currently, the directory structure is as follows:

extension
 ├-- js
 │   -- --blocked.json
 │   -- --content.js
 │   --inject.js
 └-- manifest.json

blocked.json

{
  "keyword": [
    "test",
    "test_1",
    "test_2",
    "test_3"
  ],

  "url": [
    "https://example.com/",
    "https://example_1.com/",
    "https://example_2.com/",
    "https://example_3.com/"
  ]
}

content.js

const blocked="blocked.json";

...omitted...

window.open=function(open){
  return function(url, name, features) {
    console.log("url:", url);

    fetch (blocked)
        .then(response=>response.json())
        .then(data=>formatJSON(data)));

    // loop if available in bl[0].url to compare with url
    if(url==="blacklist url"){
      console.log("url blocked!");
      return null;
    } else{
      return open.call(window, url, name, features);
    }

  };
}(window.open);

Where //.json is trying to load
function formatJSON(json){
    console.log(json);
 
    for (let bl of json) {
        console.log (bl[0].url);
    }
}

If you run with this code, the console will issue an error if blocked.json cannot get in the first place.
Also, the url that says "I can't get" seems to be getting an error trying to browse the site's json file instead of the json file in the extension, such as GET https://demosite/blocked.json404.

I look forward to hearing from you.

javascript json chrome-extension

2022-11-14 20:34

1 Answers

Relative URLs cannot be used for this purpose because they are relative to the URL of the page you are viewing.

Specify blocked.json as web_accessible_resources and .fetch().


2022-11-15 06:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.