Hi Thom,
Thanks for the suggestion.
1) No errors are reported.
I tried to print the state of ocg before and after changing its value and the console shows the value is changed successfully.
But somehow, the layers still show up in Adobe Reader.
2) The full story is as following:
we are trying to keep the PDF editable while making sure a security watermark is always present.
Currently we come with an idea to use javascript to create watermark on the fly whenever users try to make a save.
So far it seems to work OK, but it will lead an issue that more and more layers will be created when more saves are made.
When there is a timestamp in the watermark, it looks really bad.
Then I am trying to see if it is possible to make only one layer visible and leave the rest hidden.
As it happens, I have a security layer example and all the code for doing exactly what you want at www.pdfscripting.com. The example contains text that explains the technique. Which includes adding text as a watermark. There is only one bit that cannot be done from a script. Which is setting the visibility option. If you want to automate this process, then a plug-in is required to do the bit that cannot be done in JS. However, the example is only for site members.
Creating watermarks on the fly can be trouble some. They cannot be modified or removed directly with a script. And the visibility cannot be reliably controlled with a script. If you want a dynamic security warning, then a Text Annotation would be a better choice.