如何在 Manifest v3 中获取 jsonp

How to fetch jsonp in Manifest v3

提问人:Ahmed El-Tabarani 提问时间:9/28/2022 最后编辑:Ahmed El-Tabarani 更新时间:9/29/2022 访问量:661

问:

Refused to load the script 'https://dorar.net/dorar_api.json?skey=انما الاعمال بالنياتpage=1&callback=jsonp_callback_255' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Manifest v3 不允许加载外部脚本,所以我无法获取任何 API,因为每个处理 jsonp 的库都会加载一个脚本,我应该如何在 Manifest v3 中获取 jsonp ?JSONP

注意:我已经在本地文件夹中下载了 fetchJsonp,并将其导入到 file 中popup.html

<script src="./thirdparty/fetchJsonp.min.js"></script>

背景.js

chrome.runtime.onInstalled.addListener(() => {

  chrome.contextMenus.create({
    title: 'Check this hadith',
    id: 'check-hadith',
    contexts: ['selection'],
  });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  chrome.storage.local.set({ text: info.selectionText }, async () => {
    await chrome.windows.create({
      url: chrome.runtime.getURL('popup.html'),
      type: 'popup',
    });
  });
});

弹出.js

import {
  getAllHadith,
  getAllHadithInfo,
} from './utils/extractHadithInfo.js';

const searchForHadithByText = async (text, page = 1) => {
  const url = `https://dorar.net/dorar_api.json?skey=${text}&page=${page}`;
  const data = await convertToJSON(url);
  return data;
};

const convertToJSON = async (url) => {
  try {

    const data = await fetchJsonp(encodeURI(url)); // ERROR HERE!!!
    
    // rest of the code doesn't related with the error
    
    const html = he.decode(data.ahadith.result);
    const allHadith = getAllHadith(html);
    const allHadithInfo = getAllHadithInfo(html);

    const result = allHadith.map((hadith, index) => {
      return {
        ...hadith,
        ...allHadithInfo[index],
      };
    });
    return result;
  } catch (err) {
    console.error(err);
  }
};

const cards = document.getElementsByClassName('cards')[0];
chrome.storage.local.get('text', async ({ text }) => {
  const allHadith = await searchForHadithByText(text);
  const allCardsDiv = allHadith.map((_hadith) => {
    const { hadith, el_rawi, el_mohdith, source, number_or_page, grade } =
      _hadith;

    return `<div class="card">
             <p class="hadith-text">${hadith}</p>
             <div class="hadith-info">
                <p class="hadith-rawi"><span>الراوي:</span> ${el_rawi}</p>
                <p class="hadith-mohdith"><span>المتحدث:</span> ${el_mohdith}</p>
                <p class="hadith-source"><span>المصدر:</span> ${source}</p>
                <p class="hadith-number"><span>رقم الحديث أو الصفحة:</span> ${number_or_page}</p>
                <p class="hadith-grade"><span>صحة الحديث:</span> ${grade}</p>
             </div>
        </div>`;
  });

  cards.innerHTML = allCardsDiv.join('');
});

manifest.json

{

  "name": "Hadith Checker",
  "description": "Checking the selected hadith, whether it is fabricated or authentic",
  "version": "0.4",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["contextMenus", "storage", "unlimitedStorage"],
  "icons": {
    "16": "./icons/icons16.png",
    "32": "./icons/icons32.png",
    "48": "./icons/icons48.png",
    "128": "./icons/icons128.png"
  }
}

文件夹结构

- icons
+ thirdparty 
   |
   - fetchJsonp.min.js
   - he.min.js
+ utils
   |
   - extractHadithInfo.js
- background.js
- manifest.json
- popup.css
- popup.js
- README.md
javascript 谷歌浏览器 扩展 jsonp chrome 扩展清单 v3

评论

1赞 wOxxOm 9/29/2022
不需要这个库:扩展程序可以直接从 URL 简单地将文件添加到manifest.jsonfetch"host_permissions": ["https://dorar.net/"]

答:

0赞 Ahmed El-Tabarani 9/29/2022 #1

根据评论wOxxOm

不需要这个库:扩展程序可以直接从 URL 获取文件,只要您将它的站点添加到类似 “host_permissions”: [“https://dorar.net/”] 的manifest.json中

所以我是这样解决的

弹出.js

...
const convertToJSON = async (url) => {

  try {

    const res = await fetch(encodeURI(url)); // using native fetch
    const data = await res.json();

    // rest of the code are the same
    ...

manifest.json

{
    ...
    "host_permissions": ["https://dorar.net/"],
    ...
}