chrome插件,绕过CSP限制,Refused to run the JavaScript URL问题

发布于:2025-03-30 ⋅ 阅读:(34) ⋅ 点赞:(0)

问题:chrome插件使用,点击一个a标签时,遇到下列问:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:* chrome-extension://b58829fe-f006-45fb-8509-18b9abbad2d1/". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

a标签的href不是一个地址二是一个inline的JS代码。用于翻页。点击这个a标签就是执行JS。安全机制不让点。

反正就是不让点。最后通过chrome.scripting.executeScript解决。

基本原理是:把这个翻页动作的函数注入到页面,注入的函数将在目标页面的主环境中执行。然后在content.js中发个信息与主页面JS通信。实现调用原来网页本身的JS对象。

background.js如下:

/**
 * 监听来自content script的消息
 * 处理脚本注入请求,安全地将功能注入到目标页面
 */
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // 只处理INJECT_PAGE_SCRIPT类型的请求
  if (request.type === 'INJECT_PAGE_SCRIPT') {
    // 使用chrome.scripting.executeScript将代码注入到目标页面
    chrome.scripting.executeScript({
      // 指定目标标签页
      target: {tabId: sender.tab.id},
      // 注入的函数将在目标页面的主环境中执行
      func: () => {
        /**
         * 页面脚本内容 - 在目标页面中执行的代码
         * 监听来自扩展的消息,安全地与页面原有功能交互
         */
        window.addEventListener('message', function(event) {
          if (event.origin === window.location.origin && 
              event.data.type === 'ExtensionCallBpsChangePage') {
            if (typeof bps !== 'undefined' && typeof bps.changePage === 'function') {
              try {
//bps对象就是原网页的对象,这里可以直接调用。因为这部分代码是在注网页中执行。
                bps.changePage(event.data.action, ...event.data.params);
                window.postMessage({
                  type: 'BpsChangePageResult',
                  success: true
                }, window.location.origin);
              } catch (error) {
                window.postMessage({
                  type: 'BpsChangePageResult', 
                  success: false,
                  error: error.message
                }, window.location.origin);
              }
            }
          }
        });
      },
      // 指定执行环境为主页面(MAIN),可以与页面原有JS交互
      world: 'MAIN'
    }).then(() => {
      // 脚本注入成功,返回成功响应
      sendResponse({success: true});
    }).catch(error => {
      // 脚本注入失败,返回错误信息
      sendResponse({success: false, error: error.message});
    });
    // 保持消息通道开放,等待异步响应
    return true;
  }
});

content.js相关代码如下:

chrome.runtime.sendMessage({
                type: 'INJECT_PAGE_SCRIPT'
            }, (response) => {
                if (response && response.success) {
                    // 脚本注入成功后发送翻页消息
                    window.postMessage({
                        type: 'ExtensionCallBpsChangePage',
                        action: 'end',
                        params: ['hpage', 'showCurpage', 'courseList']
                    }, window.location.origin);
                    console.log('已发送翻页消息');