chrome.extension.isAllowedIncognitoAccess(function (isAllowedAccess) { if (isAllowedAccess) { chrome.runtime.getBackgroundPage(function (backgroundPage) { let sandbox = new backgroundPage.Cu.Sandbox( "http://www.example.com", { invisibleToDebugger: true } ); let result = sandbox.evaluate(` let x = 10; let y = 20; return x + y; `); console.log(result); // prints "30" }); } else { console.log("cannot access incognito mode"); } });
chrome.runtime.getBackgroundPage(function (backgroundPage) { let sandbox = new backgroundPage.Cu.Sandbox( "http://www.example.com", { visibleToDebugger: true } ); // Assume that we have untrusted code stored in the `code` variable. let code = "alert('this is a malicious script!');"; sandbox.Compartment(code, { print: false, import: function (moduleSpecifier) { throw new Error("import is not allowed"); }, export: function (name, value) { throw new Error("export is not allowed"); }, console: null, eval: function () { throw new Error("eval() is not allowed"); }, }); });In this example, we're using the `Compartment()` method to create a new sandbox compartment that will execute untrusted code. We're also specifying a set of restrictions on what the untrusted code can do. For example, we're disabling the `print()` method (which would allow the code to print messages to the console), and we're disallowing imports and exports. We're also disabling the `eval()` method, which prevents the code from executing dynamic code. Overall, the Chrome Cu Sandbox provides a powerful mechanism for executing untrusted code in a secure and isolated environment. The library is provided as part of the Chrome extension API, and is not available as a standalone package.