使用Chrome插件在页面加载完成之前执行JS注入

By | September 9, 2020

使用以下代码可以跳过chrome 插件沙盒执行JS注入
extension/manifest.json

{
  "manifest_version": 2,
  "name": "Content Script Sandbox Breakout Extension",
  "version": "1.0.0",
  "applications": {
    "gecko": {
      "id": "[email protected]"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["sandbox-breakout.js"],
      "run_at": "document_start"
    }
  ]
}

extension/sandbox-breakout.js

const overwriteLanguage = (language) => {
  Object.defineProperty(navigator, 'language', {
    get: () => language,
  });
};

// Breaks out of the content script context by injecting a specially
// constructed script tag and injecting it into the page.
const runInPageContext = (method, ...args) => {
  // The stringified method which will be parsed as a function object.
  const stringifiedMethod = method instanceof Function
    ? method.toString()
    : `() => { ${method} }`;

  // The stringified arguments for the method as JS code that will reconstruct the array.
  const stringifiedArgs = JSON.stringify(args);

  // The full content of the script tag.
  const scriptContent = `
    // Parse and run the method with its arguments.
    (${stringifiedMethod})(...${stringifiedArgs});

    // Remove the script element to cover our tracks.
    document.currentScript.parentElement
      .removeChild(document.currentScript);
  `;

  // Create a script tag and inject it into the document.
  const scriptElement = document.createElement('script');
  scriptElement.innerHTML = scriptContent;
  document.documentElement.prepend(scriptElement);
};

// Break out of the sandbox and run `overwriteLanguage()` in the page context.
runInPageContext(overwriteLanguage, 'xx-XX');

或者下面的简写:

location = 'javascript:(' + (function(){
            const overwriteLanguage = () => {
              Object.defineProperty(navigator, 'language', {
                get: () => 'xx-XX',
              });
            };
}).toString().replace(/\\n/g, ' ') +')();';

目前测试结果只有一个网站上无效: https://chrome.google.com/webstore/category/extensions?hl=en

源:https://intoli.com/blog/sandbox-breakout/

Leave a Reply