SACRAMENTO — Gov. Jerry Brown signed a bill Thursday to limit when a person’s immigration status can be disclosed in open court, a measure aimed at keeping crime victims and witnesses from exposing themselves to possible deportation when they take the stand.

SB785 by Sen. Scott Wiener, D-San Francisco, requires that a judge hold a closed hearing to consider whether the immigration status of a victim, defendant or witness is relevant before allowing it to be raised in open court.

The Legislature passed the bill as an urgency measure, meaning it takes effect immediately.

“Our goal in pursing this legislation is to ensure that immigrants feel safe going to court to testify as a victim or a witness,” Wiener said. “Immigrants are already on edge, given everything happening in this country.”

Wiener noted that federal immigration agents have detained people at California courthouses. U.S. Attorney General Jeff Sessions said agents were picking people up outside court in cases where they have no alternative because of sanctuary laws that restrict when local authorities can cooperate in enforcement of immigration laws.

“The last thing we need is for attorneys to harass immigrants on the stand by asking irrelevant questions about their immigration status,” Wiener said. “If victims feel unsafe going to court, then that undermines public safety for everyone.”

San Francisco District Attorney George Gascón said that revealing a person’s immigration status in court discourages others from coming forward to report crimes. Gascón sought the bill after a dispute with San Francisco Public Defender Jeff Adachi, whose attorneys had revealed the immigration status of alleged crime victims in several court cases in an effort to discredit them.

Adachi’s attorneys questioned whether people reporting crimes had ulterior motives for doing so — such as obtaining a visa available for some crime victims.

Adachi initially defended the practice when The Chronicle reported it last year, then said additional precautions were being taken to “ensure that what we do doesn’t create an unintended consequence.”

The bill was opposed by the California News Publishers Association, an industry group representing news media outlets. It argued that the credibility of a witness or alleged victim should be discussed in open court, where attorneys are free to object to what they consider irrelevant questions.

Under the bill, which passed the Legislature on May 10 with bipartisan support, a judge can still determine that a person’s immigration status is relevant to a case, at which point it can be raised in open court.

“This was always about public safety, not immigration,” Gascón said in a statement. “The bipartisan support this bill received is a testament to the fact that community safety benefits when immigrants can come forward without fear of consequences.”

Melody Gutierrez is a San Francisco Chronicle staff writer. Email: mgutierrez@sfchronicle.com. Twitter: @MelodyGutierrez