The detectors for grade crossing signals are actually coming from the track. An insulated rail joint is located some distance from the crossing, depending on the average speed of trains on that line. The usual location is about 30 seconds before the engine arrives at the crossing.
The rails are powered by a low voltage current, usually from track side power poles or from batteries. Using batteries and solar power is becoming more common as pole lines get taken down in the US. As the locomotive's steel wheels cross this insulated section, a short is created, which then activates the crossing signals and gates, if there are gates.
The insulated sections are on both sides of the crossing the signals stay activated until some set period of time, usually five seconds, when the signal detector no longer sees a short, meaning the last car of the train has passed. The lights and bells are then turned off and the gates rise.
It would be nice if we could use the same system for crossing signals in model railroads but causing a short would not only activate the crossing signals, it would stop the train.

The typical method for model railroad grade crossing protection are infrared detectors, which function in much the same way as the insulated track sections but use the change in light of a train passing over or between the infrared detectors to activate the crossing signals.