使用Puppeteer操作/设置样式shadowRoot [英] Manipulate / set style shadowRoot using Puppeteer

查看:19
本文介绍了使用Puppeteer操作/设置样式shadowRoot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在没有声音和共享按钮的情况下拍摄AMP故事的屏幕截图。

在我发现有一种叫做卷影DOM的东西后,我想知道如何设置Display:None There:

addStyleTag({content: '.i-amphtml-story-system-layer-buttons { display : none!important }'})

我想我是这样访问卷影DOM的。

const shadowRootInnerHTML = await page.evaluate(() => {
    return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});

这是我目前使用的

const browser = await puppeteer.launch({
  slowMo: 250,
  args: [
    '--disable-infobars',
  ]
});
const page = await browser.newPage()

await page.emulate({
  name: 'iPhone1080x1920',
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
  viewport: {
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    isLandscape: false
  }
});

await page.goto(urlToTest, {
  waitUntil: 'networkidle2',
  timeout: 0
});

const textContent = await page.evaluate(() => {
  return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});

推荐答案

Amp>Amp-Story中有多个div元素。

我们可以执行这个普通的JavaScript,它将隐藏Amp页面上的顶部幻灯片和共享按钮。

我已在此代码中添加了两种方法,您可以应用其中一种方法。

// there are multiple div elements inside amp-story
const elements = [...document.querySelectorAll("body > amp-story > div")];

elements.map(rootElement => {
  // find the shadowRoot inside if it exists
  const shadowRoot = rootElement.shadowRoot;

  if (shadowRoot) {
    /**
     * WAY 1: Find the element and apply css to it directly
     */
    // this holds the top share button and pagination slides
    const element = shadowRoot.querySelector(
      ".i-amphtml-story-system-layer"
    );

    // forcefully hide the element
    if (element) element.style.setProperty("display", "none", "important");

    /**
     * WAY 2: Append your own style to the <style> tag inside the amp shadowRoot
     */
    shadowRoot.querySelector('style').innerHTML += `.i-amphtml-story-system-layer { display : none!important }`
  }
});

基本上

  • 查找div
  • 获取shadowRoot
  • 找到元素并直接应用,或者将样式添加到标记。

样例Amp页面上的结果:

这篇关于使用Puppeteer操作/设置样式shadowRoot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆