Search code examples
pythonseleniumiframesame-origin-policycross-origin-read-blocking

SecurityError: Permission denied to access property "document" on cross-origin object error clicking on download link in iframe using Selenium Python


I am working on an automation project and I am trying to download a pdf from a website. The website only contains the pdf but the file type of the webpage is HTML. The pdf is displayed using PDF.js and the PDF.js viewer is also in an iframe.

When I tried to click the element using browser javascript, i was returned with a security error relating to cross site scripting.

SecurityError: Permission denied to access property "document" on cross-origin object

I would like to download the pdf from my script, written in python, using selenium. When I try this:

driver.find_element_by_id('download').click()

No results are produced, the download button doesn't get clicked even though I have switched focus to the iframe in selenium.

Does anybody know a solution how to download the pdf?


Solution

  • To click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

    • Using ID:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "download"))).click()
      
    • Using CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#download"))).click()
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='download']"))).click()
      
    • Note : You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    Reference

    You can find a detailed discussion in: