Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

executeScript with function #7

Open
jeprojects opened this issue Sep 13, 2023 · 6 comments
Open

executeScript with function #7

jeprojects opened this issue Sep 13, 2023 · 6 comments

Comments

@jeprojects
Copy link

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
Copy link
Owner

xvrh commented Sep 13, 2023

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
Copy link
Author

It would be great if it could be from a string

@xvrh
Copy link
Owner

xvrh commented Sep 13, 2023

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
Copy link

dom3lek commented Nov 23, 2023

@xvrh Hey, any updates about this?

@xvrh
Copy link
Owner

xvrh commented Nov 23, 2023

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

@jarrodcolburn
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants