xvrh / chrome_extension.dart

A library for accessing the chrome.* APIs available in Chrome extensions
https://pub.dev/packages/chrome_extension
BSD 2-Clause "Simplified" License
21 stars 7 forks source link

executeScript with function #7

Open jeprojects opened 1 year ago

jeprojects commented 1 year ago

Any examples of how to correctly use the executeScript method?

This doesn't seem to output anything to the browser devtools console.

chrome.scripting.executeScript(ScriptInjection(
      target: InjectionTarget(tabId: tab.id!),
      func: () {
        print('test');
      }.toJS,
    ));
xvrh commented 1 year ago

The function to pass to this API is a bit special. This is an "InjectedFunction" and it needs to be serializable. I will experiment a bit but my initial feeling is that it will be hard to support this from Dart.

Maybe we could come up with a way to create a JS function from a string:

func: 'function() { console.log("test"); }'.toJSFunction

At this point, your best alternative maybe to inject a file:

await chrome.scripting.executeScript(ScriptInjection(
    target: InjectionTarget(tabId: currentTab.id!), files: ['script.dart.js']));
jeprojects commented 1 year ago

It would be great if it could be from a string

xvrh commented 1 year ago

I tried something like that:

@staticInterop
@JS('Function')
class FunctionFromCode {
  external factory FunctionFromCode(String code);
}

void main() {
  await chrome.scripting.executeScript(ScriptInjection(
      target: InjectionTarget(tabId: currentTab.id!),
      func: FunctionFromCode('console.log("Hello from dart script");').toJS));
}

but it doesn't work because of Content Security Policy of the chrome extension EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive

dom3lek commented 10 months ago

@xvrh Hey, any updates about this?

xvrh commented 10 months ago

@dom3lek no news. Feel free to have a look and share your results. thanks

jarrodcolburn commented 1 month ago

This is not a solution... but Dart's port of Puppeteer has the method evaluate. Which run's a sting. Maybe that packages' authors have some good advice and lessons learned on how to accomplish passing JavaScript commands to browser (although Puppeteer probably isn't constrained by the same csp restriction). I may be wrong, but I think they're creating temp .js files.