Again, as the questions state, how to add extra style to node? I've tried SetAttributes and SetAttributeValue, both without any luck and couldn't find any examples anywhere. Code snippet:
// SetAttribute
arrts := map[string]string{
"border-style": "solid",
"border-color": "red",
}
err = chromedp.Run(ctx, chromedp.SetAttributes(selector, arrts))
// SetAttributeValue
err = chromedp.Run(ctx, chromedp.SetAttributeValue(selector, "style", "border-style:solid;border-color:red;"))
Tried SetAttribute both with this map and with "style": "border...", without any luck. Selector is an xpath, working with screenshot.
Both functions do not return error, they just hang
Went with calling the JS function as DevTools:
func addCss(ctx context.Context, elementType string, i int, color string) error {
var executed *runtime.RemoteObject
index := strconv.Itoa(i)
addCss := "(function addCss(type, index, color) {var elements = document.getElementsByTagName(type); var single = elements[index]; var params = \"thick solid \" + color; single.style.outline = params}(\"" + elementType + "\",\"" + index + "\",\"" + color + "\"))"
err := chromedp.Run(ctx, chromedp.EvaluateAsDevTools(addCss, &executed))
if err != nil {
return err
}
return nil
}
But I kinda feel that this might have been done nicer
I'd suggest to investigate how this can be done better with Puppeteer. If that's the case, perhaps there's a devtools protocol command you could use here.
Puppeteer seems to use a function they have already injected into the DOM:
https://github.com/puppeteer/puppeteer/blob/76b24e64e87c88a5da2fea54ca640deb41924a6b/experimental/puppeteer-firefox/lib/DOMWorld.js#L209
I ended up writing my own function inspired by theirs:
func AddCSS(ctx context.Context, css string) error {
script := `
(() => {
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(` + "`" + css + "`" + `));
document.head.appendChild(style);
})()
`
var executed *runtime.RemoteObject
err := chromedp.Run(ctx, chromedp.Evaluate(script, &executed))
return err
}
The weird arrow function definition and execution is just for scope encapsulation.
@naueramant that's actually really neat!